如何将 async await 与另一个 API 的实现代码一起使用

How to use async await with another API's implementation code

我有一个使用 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   
   }
 }