2

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 ?

1

2 Answers 2

5

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));
}
6
  • Try catch can be avoid ? If I use in my main: test().then(res => ).catch(err => ) ?
    – Mendes
    Sep 14, 2018 at 15:27
  • The try catch is optional, but considered best practice unless you can guarantee your task will never fail, which is unlikely.
    – Adam
    Sep 14, 2018 at 15:28
  • There is no need for a complicated workaround for try-catch, just use it ;)
    – Stephan T.
    Sep 14, 2018 at 15:31
  • 1
    @Mendes you would have to return the return the result from the awaited task before you can use it a promise chain like you've specified there in the form of test().then(res => ).catch(err => ) . So the function should write return await task otherwise it would return Promise with an undefined value
    – etarhan
    Sep 14, 2018 at 15:33
  • 1
    Calling test() won't return anything. You are handling the promise/async action within the function. If you want behaviour like that then you need to return a promise from your test() method. Async await expects a promise, have a read of this to understand better: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/….
    – Adam
    Sep 14, 2018 at 15:33
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.