I have tried it all. I want to fetch from my server some data in a loop, and add the ressponses in an array in the order I run the for loop.
I am thinking the answer is in recursion, but tried it several times and failed.
I am using 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);
});
}
Maybe that code is completely wrong, it is anyway like the 7th time I write it... I tried with promises, async/await, sync, and now recursion...