Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use async await function object in Javascript?

Say I have a function object-

setObj : function(a,b){
    obj.a = a;
    obj.b = b;
}

If I have to use async & await on this function object, how do I do it?

If the same was written in function (function way), say-

async function setObj(a,b){
    obj.a = a;
    obj.b = b;
}

await setObj(2,3);

This works fine. But, how do I do it in case of function object?

like image 303
bozzmob Avatar asked Dec 10 '15 20:12

bozzmob


People also ask

Can I use async await in JavaScript?

Note: The await keyword is only valid inside async functions within regular JavaScript code. If you use it outside of an async function's body, you will get a SyntaxError . await can be used on its own with JavaScript modules.

When should I use async await JavaScript?

async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

How do you use await in JavaScript?

The await operator is used to wait for a Promise. It can be used inside an Async block only. The keyword Await makes JavaScript wait until the promise returns a result. It has to be noted that it only makes the async function block wait and not the whole program execution.

How does async await work?

The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.


1 Answers

If I understand your question correctly, you can just use the async keyword in front of the method declaration:

let obj = {};
let myObj = {
    async setObj(a,b) {
        obj.a = a;
        obj.b = b;
    }
}

See http://tc39.github.io/ecmascript-asyncawait/#async-methods

UPDATE

You cannot use await outside of an async function. In order to use this you have to wrap that call to await setObj(2, 3):

async function consoleLog() {
    await myObj.setObj(2, 3);
    console.log(obj.a + obj.b);
}

consoleLog();
like image 140
Ben March Avatar answered Sep 21 '22 05:09

Ben March