How to use async await function object in Javascript?

bozzmob picture bozzmob · Dec 10, 2015 · Viewed 20.2k times · Source

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?

Answer

Ben March picture Ben March · Dec 10, 2015

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