简体   繁体   中英

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);

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM