简体   繁体   English

我想让回调在执行下一行代码之前等待响应

[英]I want to make the callback wait for the response before executing the next lines of code

I want to make the callback wait for the response before executing the next lines of code.我想让回调在执行下一行代码之前等待响应。 I did try to make the callback async then await for the response, but that didn't work.我确实尝试使回调async然后await响应,但这不起作用。

async signup(parent, args, ctx, info) {

    const email = args.email;
    let res;
    verifier.verify(email, function(err, response) {
      if (err) console.log(err);
      else {
        res = response.success;
        console.log('before', res); // true or false
      }
    });
    console.log('after', res); // undefined
}
async function signup (parent, args) {
  return new Promise(function(resolve, reject) {
    verifier.verify(args.email, function(err, response) {
      if (err) { 
        reject(err);
      }
      else {
        resolve(response.success);
      }
    });
  });
}

Create a function and execute it after getting response创建一个function,得到响应后执行

async signup(parent, args, ctx, info) {

const email = args.email;
let res;
verifier.verify(email, function(err, response) {
  if (err) console.log(err);
  else {
    res = response.success;
    console.log('before', res); // true or false
    nextfun(res)
  }
});
}


function nextfun(res) {
 console.log(res)
}
 async signup(parent, args, ctx, info) {

    let res = await new Promise(function(resolve, reject) {
      verifier.verify(args.email, function(err, response) {
        if (err) {
          reject(err);
        } else {
          resolve(response.success);
        }
      });
    });

    console.log('after', res); // response.success

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM