Search code examples
node.jsvonage

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


I have a user register function which is using async/await and I need to implement some code from another API. When I try to integrate it I get an error that I can't use await outside an async function.

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);
      }
}

Solution

  • You need to make the callback function async, and most likely wrap the entire code in a try catch block to handle errors.

    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   
       }
     }