我正在改编 library that uses callback使用 promise 。它在我使用 then()
时有效,但在我使用 await
时无效。
> dbc.solve
[AsyncFunction]
> await dbc.solve(img)
await dbc.solve(img)
^^^^^
SyntaxError: await is only valid in async function
dbc.solve 的代码是:
module.exports = DeathByCaptcha = (function() {
function DeathByCaptcha(username, password, endpoint) {
...
}
DeathByCaptcha.prototype.solve = async function(img) {
return new Promise(
function(resolve, reject) {
...
}
);
};
})();
我相信这与 solve
是 prototype
的成员有关,但我找不到任何相关信息。我发现节点没有 always supported async await for class methods ,所以我从节点 7 升级,现在我使用的是节点 9.4.0。
最佳答案
您没有正确阅读该错误消息:问题不在于您正在调用的函数,而在于您在中的函数。
你可以
(async function(){
await dbc.solve(img);
// more code here or the await is useless
})();
请注意,节点的 REPL 中应该很快就不再需要这个技巧了:https://github.com/nodejs/node/issues/13209
关于javascript - 使用异步需要异步功能,但我的功能是异步的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48686057/