使用 async 需要 async 函数,但我的函数是 async [英] Using async requires async function, but my function is async
问题描述
我正在改编一个使用回调的库来使用承诺.当我使用 then()
时它可以工作,但是当我使用 await
时它不起作用.
I'm adapting a library that uses callback to use Promises. It's working when I use then()
, but it doesn't work when I use await
.
> dbc.solve
[AsyncFunction]
> await dbc.solve(img)
await dbc.solve(img)
^^^^^
SyntaxError: await is only valid in async function
dbc.solve 的代码是:
The code for dbc.solve is:
module.exports = DeathByCaptcha = (function() {
function DeathByCaptcha(username, password, endpoint) {
...
}
DeathByCaptcha.prototype.solve = async function(img) {
return new Promise(
function(resolve, reject) {
...
}
);
};
})();
我相信这与 solve
是 prototype
的成员有关,但我找不到任何关于它的信息.我发现该节点没有始终支持类方法的异步等待,所以我从节点 7,现在我使用节点 9.4.0.
I believe this has something with the fact solve
is member of prototype
, but I couldn't find any information about it. I found that node didn't always supported async await for class methods, so I upgraded from node 7, now I'm using node 9.4.0.
推荐答案
您没有正确阅读该错误消息:问题不在于您正在调用的函数,而在于您所在的函数强>.
You don't read that error message right: the problem isn't the function you're calling but the function you're in.
你可以这样做
(async function(){
await dbc.solve(img);
// more code here or the await is useless
})();
请注意,节点的 REPL 中应该很快不再需要此技巧:https://github.com/nodejs/node/issues/13209
Note that this trick should soon enough not be needed anymore in node's REPL: https://github.com/nodejs/node/issues/13209
这篇关于使用 async 需要 async 函数,但我的函数是 async的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!