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.

3

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The first function does return something it is the second function that doesn't return anything.
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 ah that makes sense now, thanks for clarifying!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.