0

I have a function which get a list of ids from a request I'm doing with axios.

Then, I display the list of ids in my main function.

const axios = require('axios');

function getListOfIds(){
  var idlist = [];

  var request = {
      ...
  };

  var config = {
    ...
  };

  axios.get(request.url, config)
    .then(res => {
      ...
      idlist.push(deal.thread_id);
      //LIST FULL OF THINGS HERE, VERIFIED BY LOGS
      ...
    })
    .catch(err => {
      console.log('Error: ', err.message);
    });

  return idlist;
}


async function main() {
  var ids = getListOfIds();
  ids.forEach(function(id) {
    console.log(id);
  });
  //NOTHING, LIST EMPTY !
}

main();

But the result is always empty, even if I'm sure there is id pushed in the list.

It seems that I display the result before my function is finished (sync/async). I want to make this simpliest as possible, I don't need async treatment here.

How can I do it ?

user2178964
  • 124
  • 6
  • 16
  • 40
  • 1
    Simplest as possible is understanding promises, callbacks and async/await! You can't avoid 'async treatment'. – Evert Aug 08 '22 at 15:48
  • Can you put a log statement in side Axios `then` block and one below `getListOfIds` call; and then share the order in which the logs are printed? – Haroon Azhar Khan Aug 08 '22 at 15:56
  • you can pass a callback to the `getListOfIds` that will give you the ids and you can console log your ids. Or you use the async/await route. – urchmaney Aug 08 '22 at 16:00

0 Answers0