By Mendes


2018-09-14 15:25:02 8 Comments

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 comments

@NullPointer 2018-09-14 15:58:42

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.

@Adam 2018-09-14 15:26:54

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

@Mendes 2018-09-14 15:27:55

Try catch can be avoid ? If I use in my main: test().then(res => ).catch(err => ) ?

@Adam 2018-09-14 15:28:51

The try catch is optional, but considered best practice unless you can guarantee your task will never fail, which is unlikely.

@Stephan T. 2018-09-14 15:31:13

There is no need for a complicated workaround for try-catch, just use it ;)

@Mendes 2018-09-14 15:32:14

If i call test().then( res => ).catch( err => //error throwed orginally by task), this is correct ?

@etarhan 2018-09-14 15:33:03

@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

@Adam 2018-09-14 15:33:40

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/….

Related Questions

Sponsored Content

19 Answered Questions

[SOLVED] How and When to use `async` and `await`

5 Answered Questions

[SOLVED] Using async/await for multiple tasks

39 Answered Questions

[SOLVED] JavaScript closure inside loops – simple practical example

4 Answered Questions

7 Answered Questions

[SOLVED] Why do we need middleware for async flow in Redux?

5 Answered Questions

[SOLVED] HttpClient.GetAsync(...) never returns when using await/async

3 Answered Questions

[SOLVED] Do you have to put Task.Run in a method to make it async?

6 Answered Questions

[SOLVED] What is the purpose of "return await" in C#?

5 Answered Questions

[SOLVED] How to safely call an async method in C# without await

10 Answered Questions

[SOLVED] AngularJS : Initialize service with asynchronous data

Sponsored Content