0

I am having a downstream API call which is basically returning a Promise object instead of resolving it and executing it on point. This is how I am calling the downstream:

const response = testClient.getSession(sessionId);

When I console.log(response) it is prinitng as Promise { <pending> } instead of desired result which it shoudl print from the downstream.

Having known very little about Async/Await, Promises etc I would like to know whihc category does it fall in? And how do I execute that promise first and do the rest of the steps.

However, I have found a temporary work around like this:

 response.then(function(result) {
      console.log(result.body);
 });

But ideally I would want to store the result into response object then and there itself. Please help me understand this. Thanks in advance

  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – sinanspd Mar 26 '21 at 06:50

1 Answers1

1

What you called a temporary workaround using then is actually the correct way of waiting on the Promise to be fulfilled. You cannot 'force' it to be fulfilled, because the code will execute as fast as it can and allow you to carry on working until then (that's the point of promises) - but you can wait on it to be fulfilled:

You ought also to check to see if the promise gets 'rejected' using catch - ie produces an error:

 response.then( function(result) {
    console.log(result.body);
 }).catch( function(error) {
    console.log(error);
});

To use await:

async function thingy(){
    const response = await testClient.getSession(sessionId);
}

To use await and check for errors:

async function thingy(){
    try {
        const response = await testClient.getSession(sessionId);
    } catch (error) {
        console.error(error);
    }
}

Note that when using async, you do generally need to be in a function declared as async.

The idea of the Promise is to allow your program to carry on doing things whilst you wait for the promise to be fulfilled/rejected - for example, you might make several requests at once, and wait for them all:

Promise.all([
    getStuff('one'),
    getStuff('two'),
    getStuff('n')
]);
FZs
  • 16,581
  • 13
  • 41
  • 50
Lee Goddard
  • 10,680
  • 4
  • 46
  • 63