i need access all axios data after for loop

Viewed 25

I'm making a simple word combinatiion website. and as a final step, I need all possible word in one string so I write code like this

const fs=require('fs');
const axios=require('axios')
function test(want){
    const res=axios.get("http://api.dictionaryapi.dev/api/v2/entries/en/"+want);
    const datapromise=res.then((res)=>res.data);
    return datapromise
}
fs.readFile('./input.txt','utf-8',function(error,data){
    //console.log("console log")
    var array=data.toString().split("\n");
    fs.writeFile("./log.txt","",(err)=>{});
    var res=""
    for(i in array){
          test(array[i]).then((data)=>(data)=>res+=data[0].word+"<br>").catch(/*(data)=>console.log(data.code)*/);
    }
    console.log(res);
})

But this code isn't work. console.log(res); is executed first and followed by for loop. How can I fix it?

1 Answers

Without knowing much about Axios I can tell that axios.get and therefore the test function is going to be async. This means console.log here will always run first here as a result. Test ends up returning a promise that will resolve at a later time.

I'd do something like this (assuming you don't have async/await available):

var res= "";
var promises = [];
for(i in array) {
  promises.push(
    test(array[i]).then((data) => res+=data[0].word + "<br>")
  );
}
Promise.all(promises).finally(() => {
  console.log(res);
});

Other notes:

  1. The catch here is being called but nothing is being passed in - this may result in an error
  2. The then has a nested function that I imagine wouldn't ever be called (data) => (data) => this is basically creating a 2nd nested function. I don't think it'd get called.
Related