Search code examples
javascriptasync-awaites6-promise

return does not await async function


In the following code, return does not return the awaited value. What can I so the the promise will be resolved before returning. Hence I want result to be SUCCESS instead of a promise.

const foo = async()=>{
    try{
        let a = await new Promise((resolve)=>{
            resolve('SUCCESS')
        })
        console.log("this is inside the try block");
        return a
    }catch{
        console.log('error')
    }
}
let result = foo();
console.log(result);


Solution

  • foo is an async function it will return a promise. To get the result of the promise, you will need to chain a then method to it:

    const foo = async()=>{
        try{
            let a = await new Promise((resolve)=>{
                resolve('SUCCESS')
            })
            console.log("this is inside the try block");
            return a
        }catch{
            console.log('error')
        }
    }
    
    foo().then(result => console.log(result));
    

    UPDATE:

    To use the returned value, you can use it inside the then method or call another function with the result.

    foo().then(result => {
      console.log(result);
      //do what you want with the result here
    });
    

    OR:

    foo().then(result => {
      someFunction(result);
    });
    
    function someFunction(result) {
       console.log(result);
      //you can also do what you want here
    }