我都试过了.我想从服务器获取循环中的一些数据,并按照运行for循环的顺序将Response添加到数组中.
我认为答案是递归的,但try 了几次,都失败了.
我正在使用AXIOS:
let currentPhraseWordAssign = [];
function addPartOfSpeechAndWordPhrasesToFullScript () {
assignPartOfSpeechAndAddToPhraseArray(["phrase", "run"]).then(() => {console.log(currentPhraseWordAssign)});
}
async function assignPartOfSpeechAndAddToPhraseArray (phrase) {
if(currentPhraseWordAssign.length >= phrase.length) {
console.log(currentPhraseWordAssign);
currentPhraseWordAssign = [];
return;
}
let word = phrase[currentPhraseWordAssign.length];
axios({
method: 'get',
url: `http://localhost:9200/english_minus_verbs/_search`,
headers: {
'Content-Type': 'application/json'
},
data: {
_source: ["part_of_speech"],
query: {
term: {
word: word,
}
}
}
}).then((r) => {
try {
currentPhraseWordAssign.push({word: word, partOfSpeech: r.data.hits.hits[0]._source.part_of_speech});
}catch (e) {
currentPhraseWordAssign.push({word: word, partOfSpeech: 'verb'});
}
}).then(()=>{
assignPartOfSpeechAndAddToPhraseArray(phrase);
});
}
也许那个代码完全错了,反正就像我第七次写它...我try 了promise 、异步/等待、同步和现在的递归...