How to use async await function object in Javascript?
Asked Answered
Q

4

20

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?

Quinquennial answered 10/12, 2015 at 20:8 Comment(0)
D
23

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();
Despatch answered 10/12, 2015 at 20:18 Comment(8)
It says missing : after property id. This is what I have tried- gist.github.com/bozzmob/a36f0d28310df88f0a5dQuinquennial
In your Gist, move the async keyword in front of "function" after the ":"Despatch
See my comments in your Gist, you are using the "await" keyword wrong, it must be inside an async function.Despatch
Please have a look at the "Update 1" in gist. I am getting the following error on doing the changes - SyntaxError: missing } after property list.Quinquennial
Ben's spot on. Check out my updated answer which works with your code.Latonya
You can use the Babel REPL to try this, I have set it up for you: tinyurl.com/zzvrzmvDespatch
Thanks a lot both of you! I did learn more than 1 way of doing this. :)Quinquennial
Specifying a key din't work func1: async func1() {}. Excellent, searched all over the internet. Thank you for the solution.Polis
L
8

Use the same async keyword in your object's property:

(async function () {
  var obj = {};
  console.log("hello");

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

  await setObj(2,3);

  console.log(obj.a+obj.b);
})();

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.

Latonya answered 10/12, 2015 at 20:17 Comment(4)
I tried this approach, I get an error saying a semicolon is missing. Have a look at my code- gist.github.com/bozzmob/f5ef1c0eff9d7e7f853dQuinquennial
Is setObj a property inside an object? For example: let someFunctions = {setObj: async function (a, b) {...}};. Your code won't run in the gist, since you're using a colon outside of an object. Alternately, you can do let setObj = async function (a, b) {...};Latonya
Please check "Update 1" on the same link(gist.github.com/bozzmob/f5ef1c0eff9d7e7f853d) Still facing the same issue.Quinquennial
And "Update 2" as well. I have tried both the solutions you told. Please can you update your current answer here with the working solution?Quinquennial
G
4

using arrow functions work as well

const myObject = {
   myFunc: async () => {
     await myResultHere
   }
}

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

const useFunc = async () => {
   const res = await myObject.myfunc();
} 
Gothard answered 14/9, 2018 at 8:58 Comment(0)
I
1

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:

const Object = {
    async asyncFunction() {
        await MyExamplepromise
    }
}

As a variable:

const myFunc = async function () { await MyExamplepromise }

// this is how execute the function expression
// first () operator to execute, and use .then get access the resolved value
myFunc().then((val) => { console.log(val) })

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.

Irresoluble answered 14/9, 2018 at 8:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.