Why are the output results different?

Viewed 161

async function fn1() {
  return 1
}
async function fn2() {
  return Promise.resolve(1)
}

function fn3() {
  return Promise.resolve(1)
}

function fn4() {
  return Promise.resolve(Promise.resolve(1))
}
console.log(fn1()); //Promise {<fulfilled>: 1}
console.log(fn2()); // Promise {<pending>}
console.log(fn3()); // Promise {<fulfilled>: 1}
console.log(fn4()); // Promise {<fulfilled>: 1}

When I run fn2(), it outputs Promise { pending }.

Why is fn2() Promise { pending } rather than Promise {fulfilled: 1}?

3 Answers

fn2() is kinda deceiving. Returning a Promise from an async function results in code that MUST be awaited or then()ed before it even tries to resolve. Here's a starting point to understand why.

EDIT: This is incorrect. See @VLAZ's comment below.

Async function always return a promise. So

Fn2 function returning two promise one by async function and one by your return statement.

And return statement will full fill the async function promise and will not full fill the return statement promise that is why you are getting this output

Both function1 and function2 are async, but in case of function 1 you are directly returning the value where as in function2 you are returning a promise. Promise always returns a promise in either case(resolve or reject). Before the promise could resolve,function2 has already returned the statement. You could use await for promise to either resolve or reject before returning the value.

Related