如何在Javascript中使用异步等待函数对象? [英] 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;
}
如果我必须使用async&等待这个函数对象,我该怎么做?
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?
推荐答案
如果我理解你的问题,你可以使用方法声明前面的 async
关键字:
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;
}
}
参见 http://tc39.github.io/ecmascript-asyncawait/#async-methods
更新
您不能在之外使用
await
异步功能。为了使用它,你必须将该调用包装到 await setObj(2,3)
:
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();
这篇关于如何在Javascript中使用异步等待函数对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!