Skip to content Skip to sidebar Skip to footer

Async/await Return Promise { }

my question is: why does this log 'promise {pending}' despite of i used async/await? I checked similar questions and answers on them and it seems like it should be okay but it is n

Solution 1:

async-await is really just syntactic sugar for promises, it doesn't make asynchronous code run synchronously (i.e. it doesn't block code execution). Your code is equivalent to the following:

functionsampleFunc() {
    returnnewPromise(function(resolve) {
        rp({
            uri: 'http://google.com',
            jar: true
        }).then(function(sample) {
           resolve(sample);
        });
    });
}

functionf() {
    returnnewPromise(function(resolve) {
        sampleFunc().then(function(result) {
            resolve(result);
        });
    });
}

console.log( f());

(Yes, I know the above code demonstrates an anti-pattern. It's for illustrative purposes)

As you can see, what an async function really does is to implicitly return a promise that gets resolved with the value you eventually return inside the function (or rejected if you throw something). This is why async-await can only be used on functions and thus isn't applicable on the top level.

The context that called the function is entirely agnostic to the fact that the function is async, it just calls the function, gets a promise back and moves on to the next line of code. Your console.log() lives in this outside context and only sees the promise that was returned.

Post a Comment for "Async/await Return Promise { }"