Javascript: Return a promise inside async function

Both functions return a Promise.

const [result1, result2] = await Promise.all([promise1, promise2])
//HERE
return [result1, result2]

Where I wrote HERE you can access to result1 and result2 var that are the results of the promises.

await is an alternative to call then on Promise and its form is also more readable than

Promise.all([promise1, promise2]).then(function(results){

});

If you have multiple sequentially requests using await is a better choice

var response1= await promise1   
var response2=await promise2

against

promise1.then(function(){
    promise2.then(function(){
       promise3.then(function(){
       })
    })
})

EDIT

In the first function the keyword async is useless, the function test will return a Promise

The second function will return a Promise where you see the keyword await. When the awaited promise will resolved the execution inside the function continue and you can access to result of the promise

EDIT 1

MaybeI understand what you mean, the async keyword encapsulate your return value into a promise that has as resolved value what you have returned


I would think the way async functions works in respect to the return value is it checks whether that value is wrapped in a Promise object, and if not, does it automatically. If you explicitly return a Promise, then the function does nothing with it. I tested this out by returning a new Promise inside an async function:

async function test(){
var duration = resolveAfter(500)
    return new Promise((resolve, reject) =>{})
}

var neverresolved = test()

The result is neverresolved contains a Promise that's always in the pending state, as expected.


I think you're effectively calling synchronous-like functions with await within the promise chain which, according to this answer:

You are perfectly free to call either synchronous functions within the promise chain (from within .then() handlers) or asynchronous functions that then return a new promise.

When you return something from a .then() handler, you can return either a value (which becomes the resolved value of the parent promise) or you can return another promise (which chains onto the previous promise) or you can throw which works like returning a rejected promise (the promise chain becomes rejected).

Tags:

Javascript