Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

javascript - Using async requires async function, but my function is async

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

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) {
        ...
      }
    );
  };
})();

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't read that error message right: the problem isn't the function you're calling but the function you're in.

You may do

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

Note that this trick should soon enough not be needed anymore in node's REPL: https://github.com/nodejs/node/issues/13209


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...