1
votes

I'm trying to understand the following 2 sample functions using async-await and promise.

I expect both functions to return "output", but the function using promise returns an undefined instead.

Why is that the case? I'm already returning the value in promise.resolve().then() but there's no value returned after all.

I encountered this problem while working on my project. I was using the promise approach to return a value but there's no value returned. I then solved it using async-await, but I couldn't understand why?

async function asyncFunction(input) {
  try {
    let output = await Promise.resolve("output");
    return output;
  } catch (err) {
    console.log(err);
  }
}

function promiseFunction(input) {

    Promise.resolve().then(function() {
      return "output";
    }).catch(function(err){
      console.log(err);
    })
}

async function run() {
  let a = await asyncFunction();
  let b = await promiseFunction(); 

  console.log("async function output: " + a); //async function output: output
  console.log("promise function output: " + b); //promise function output: undefined
}

run();


I expect both asyncFunction() and promiseFunction() to return the value "output", but promiseFunction returns undefined instead.

1
you aren't returning anything from promiseFunctionDaniel A. White
You cannot return from an async call. Possible duplicate of: stackoverflow.com/q/6847697/8076386Rohit Kashyap
thanks for the link @RohitKashyap found a more comprehensive answer stackoverflow.com/questions/14220321/… through thereDavid Nge

1 Answers

2
votes

async functions always return promises. If you omit a return statement in a normal function like:

function doSomething(x) {
  x.y = 2;
}

then it returns undefined.

doSomething({}) === undefined // true

If you omit a return statement in an async function

async function doSomething(x) {
  x.y = 2;
}

it returns a promise that resolves with undefined

doSomething({}).then(result => result === undefined); // resolves to be true

In your non async function, you're not returning anything. You need to return the Promise.resolve().then(...) line. This is one of the benefits of using async/await syntax. No need to worry about properly chaining your promises and returning. Just do your work, await where needed, and return the value.