0

I have used async/wait a little within functions. And I know about callbacks but for some reason I can't get what i want to work. This is essentially what I want to do.

T.get('friends/ids', myAcc, function(err, data, response){
    friends = data;
});
console.log(friends);

what happens is it does the console log before getting the friends.

i know if I do this, it will work

T.get('friends/ids', myAcc, function(err, data, response){
    console.log(data);
});

but how can I wait for the function its self to complete? Without surrounding them with another async/aawait function?

  • 2
    Why don't you want to do the log inside the callback? The point of the callback is that it isn't called until after the async operation is done and the data is available. – nnnnnn Oct 01 '17 at 00:39
  • Because I want to save the information for later use. – Harrison Hayes Oct 01 '17 at 00:40
  • I have to then use the data later to compare its contents with another set of dat I'm retrieving in the same way. I want to wait for these sets of data to be completely loaded, before I start doing anything with them. How would I be going about this? – Harrison Hayes Oct 01 '17 at 00:50
  • You can use `Promise` constructor – guest271314 Oct 01 '17 at 01:04
  • You can use `Promise.all()`, as described in some other questions like [this one](https://stackoverflow.com/questions/38426745/how-do-i-return-the-accumulated-results-of-multiple-parallel-asynchronous-func) or [this one](https://stackoverflow.com/questions/10004112/how-can-i-wait-for-set-of-asynchronous-callback-functions) (both of those examples are doing async calls in a loop, but you can also use `Promise.all()` with async calls that aren't in a loop). – nnnnnn Oct 01 '17 at 01:06

1 Answers1

0

You can use Promise constructor

(async() => {
  let friends = await new Promise((resolve, reject) => {
                  T.get('friends/ids', myAcc, function(err, data, response) {             
                    if (err) {
                      reject(err);
                      return;
                    }
                    resolve(data);
                  });
                }).catch(err => err);
  console.log(friends);
})();
guest271314
  • 1
  • 15
  • 104
  • 177