使用async需要异步功能,但我的功能是异步的

rod*_*gas 5 javascript promise async-await

我正在调整使用回调来使用Promises.它在我使用时then()起作用,但在我使用时它不起作用await.

> dbc.solve
[AsyncFunction]
> await dbc.solve(img)
await dbc.solve(img)
^^^^^

SyntaxError: await is only valid in async function
Run Code Online (Sandbox Code Playgroud)

dbc.solve的代码是:

module.exports = DeathByCaptcha = (function() {
  function DeathByCaptcha(username, password, endpoint) {
    ...
  }

  DeathByCaptcha.prototype.solve = async function(img) {
    return new Promise(
      function(resolve, reject) {
        ...
      }
    );
  };
})();
Run Code Online (Sandbox Code Playgroud)

我相信这有事实solve是成员prototype,但我找不到任何有关它的信息.我发现节点并不总是支持异步等待类方法,所以我从节点7升级,现在我正在使用节点9.4.0.

Den*_*ret 15

你不读该错误信息是正确的:问题不在于你调用该函数,但你的函数.

你可能会这样做

(async function(){
    await dbc.solve(img);
    // more code here or the await is useless
})();
Run Code Online (Sandbox Code Playgroud)

请注意,节点的REPL中不再需要这个技巧了:https://github.com/nodejs/node/issues/13209

  • @rodorgas这很棘手,我们大多数人都被欺骗了一次,但如果你足够谨慎我不认为这是不明确的.而且我没有看到任何明显更好的信息. (2认同)

mes*_*ill 6

SyntaxError: await is only valid in async function- 就像错误告诉你的那样,你只能await在标记为的函数内使用async.所以你不能await在其他地方使用关键字.

https://basarat.gitbooks.io/typescript/docs/async-await.html

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-7.html

例子:

function test() {
  await myOtherFunction() // NOT working
}

async function test() {
  await myOtherFunction() //working
}
Run Code Online (Sandbox Code Playgroud)

您还可以创建匿名回调函数async:

myMethod().then(async () => {
  await myAsyncCall()
})
Run Code Online (Sandbox Code Playgroud)