skip to Main Content

If I call an async function that doesn’t explicitly return anything from the await, will it return a resolved Promise? Or Void? Something else?

For example an IIFE like this, or this but it being called in the global scope by sync code:

(async myFunc() {
   const list = await someFunc();
   const anotherList = someOtherFunc(list);
   console.log(anotherList);
})();

I have it in my head that all async functions return a Promise.

2

Answers


  1. If code inside the async IIFE is sync and no promise returned than it returns a resolved fullfilled promise. If it contains await or returns a promise it returns a pending promise:

    let promise = (async () => {
    
    })();
    
    console.log(promise.toString());
    
    promise = (async () => {
       const list = await 1;
    })();
    
    console.log(promise.toString());

    enter image description here

    Login or Signup to reply.
  2. Asynchronous functions are just a wrapper around the Promise object. Normally, one creates a promise and passes in a callback function. When ready, the programmer calls the then method, et cetera. When using the async keyword, it simply abstracts that system. Therefore, it will always return a promise, even if you return something else, because it isn’t actually returning what you return.

    console.log((async () => {
        const list = await someFunc();
        const anotherList = someOtherFunc(list);
        console.log(anotherList);
    })().toString());
    
    console.log((async () => {
        const list = await someFunc();
        const anotherList = someOtherFunc(list);
        console.log(anotherList);
        return "foo";
    })().toString());
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search