1

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.

David Nge
  • 59
  • 6

1 Answers1

2

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.

CollinD
  • 7,304
  • 2
  • 22
  • 45
  • The first function does return something it is the second function that doesn't return anything. – Musa Sep 29 '19 at 18:44
  • Ah thanks, fixed that. Had initially used "first" because it was the first approach OP used, but I can see how that would be confusing. – CollinD Sep 29 '19 at 19:33
  • @CollinD ah that makes sense now, thanks for clarifying! – David Nge Oct 01 '19 at 07:01