使用async需要异步功能,但我的功能是异步的 [英] Using async requires async function, but my function is async
问题描述
我正在调整使用回调的库以使用Promises。它在我使用 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需要异步功能,但我的功能是异步的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!