Await used after promise initialized

Viewed 218

I would like to connect mongoDb and execute code asynchronously.

async function test() {
    let task = asyncTask() //return a promise
    //function still running
    await task
    //code executed only if task is resolved
}

Using await like that is correct ?

2 Answers

Yes, if you use await with an async function then the code will block until the promise has either resolved or failed. You should wrap your await block in a try catch to handle any errors.

async function test() {
    let task = asyncTask()
    //function still running
    try {
        await task
        //code executed only if task is resolved
    } catch (err){
        //Something went wrong
        throw new Error(err);
    }
}

Using async/await has the same functionality as a promise, but just provides a more synchronous way of writing your code.

If you wanted to rewrite the code as a promise then it would look like:

function test() {
    myPromise('some arguments')
    .then(result => console.log(`Task completed: ${result}`);)
    .catch(err => console.error(err));
}

async/await

async:The word async before a function means one simple thing: a function always returns a promise.

await:The keyword await makes JavaScript wait until that promise settles and returns its result.

Here

  async function test() {
    let task = asyncTask() //return a promise
    //function still running
    await task
    //code executed only if task is resolved
}  

The function execution “pauses” at the line (await task) and resumes when the promise settles, with task becoming its result.

Let’s emphasize: await literally makes JavaScript wait until the promise settles, and then go on with the result.

If a promise resolves normally, then await promise returns the result. But in case of a rejection it throws the error .

1. Either as already said in answer We should catch that error using try..catch

async function test() {
    let task = asyncTask()
    //function still running
    try {
        await task
   } catch (err){
       throw new Error(err);
    }
}

2. If we don’t have try..catch, then the promise generated by the call of the async function test() becomes rejected. We can append .catch to handle it:

async function test() {
        let task = asyncTask() //return a promise
        //function still running
        await task
        //code executed only if task is resolved
    } 
 test().catch(//error);

More If .catch is not there, then we get an unhandled promise error. We can catch such errors using a global event handler.

Related