0

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);
Phantom
  • 423
  • 1
  • 5
  • 13
  • 1
    You still need to handle the promise; `foo().then(result => console.log(result))`, for example. Async/await is just syntactic sugar for promises, it can't magically synchronise an asynchronous process. – jonrsharpe Feb 22 '20 at 21:49
  • how do I assign `SUCCESS` to result? – Phantom Feb 22 '20 at 21:53
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jonrsharpe Feb 22 '20 at 21:58

1 Answers1

1

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
}
Addis
  • 2,480
  • 2
  • 13
  • 21