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?
You can simply put the
async
keyword on any function, not only function declarations but also function expressions and methods of object. For example:As an method of an object:
As a variable:
Also notice that an async function returns a promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.
If I understand your question correctly, you can just use the
async
keyword in front of the method declaration: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 toawait setObj(2, 3)
:Use the same
async
keyword in your object's property:Note that the entire code is wrapped in an asynchronous self-invoking function. This is needed, otherwise the
await setObj
will not be able to run correctly.using arrow functions work as well
using this: Since the function is an async function, it will run asynchronously. If you want to run this with await, you will have to use it inside an async function