如何将异步等待与其他API的实现代码一起使用

问题描述

我有一个使用async / await的用户注册功能,我需要从另一个API实现一些代码。当我尝试集成它时,出现一个错误,我无法在异步函数之外使用await。

exports.register = async (req,res) => {
  // some logic here

  nexmo.verify.request(
    {
      number: formattedMobile,brand: "My Brand",code_length: "4",},(err,result) => {
      if (err) {
        // If there was an error,return it to the client
        return res.status(500).send(err.error_text);
      }
      // Otherwise,send back the request id. This data is integral to the next step
      const requestId = result.request_id;
      const salt = await bcrypt.genSalt(12);
      const hashedPassword = await bcrypt.hash(password,salt);
    
      const createdUser = new User({
        name: name,email: email,mobile: formattedMobile,password: hashedPassword,});
    
      try {
        await createdUser.save();
        res.status(200).send({ user: createdUser._id,otp: requestId });
      } catch (err) {
        res.status(500).send(err);
      }
}

解决方法

您需要制作回调函数async,最有可能将整个代码包装在try catch块中以处理错误。

async (err,result) => {
      if (err) {
        // If there was an error,return it to the client
        return res.status(500).send(err.error_text);
      }
   
      try {
      // Otherwise,send back the request id. This data is integral to the next step
      const requestId = result.request_id;
      const salt = await bcrypt.genSalt(12);
      const hashedPassword = await bcrypt.hash(password,salt);
    
      const createdUser = new User({
        name: name,email: email,mobile: formattedMobile,password: hashedPassword,});
    
      try {
        await createdUser.save();
        res.status(200).send({ user: createdUser._id,otp: requestId });
      } catch (err) {
        res.status(500).send(err);
      }
    } catch(err) {
      console.log(err);//do whatever error handling here   
   }
 }