Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...