如何在async/await实现的注册函数中整合第三方API并解决await报错
错误根因
报错的核心是await的使用范围不合法:await 只能在被声明为async的函数内部使用,你当前把await写在了nexmo.verify.request的回调函数(err, result) => {}里,而这个回调没有加async修饰,因此触发语法报错。
另外你的原代码还存在语法结构缺失问题:nexmo.verify.request的调用没有闭合括号、回调函数的括号也未写完。
解决方案
方案1:最小改动,直接给回调加async修饰
只要在回调函数前加async关键字,就能让内部的await合法生效,修正后的完整代码如下:
exports.register = async (req, res) => { // 此处省略部分业务逻辑 nexmo.verify.request( { number: formattedMobile, brand: "My Brand", code_length: "4", }, async (err, result) => { if (err) { // 若出现错误,将错误返回给客户端 return res.status(500).send(err.error_text); } // 否则返回requestId,该数据是后续流程的必需依赖 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); } } ) }
方案2:更符合async/await规范的写法(推荐)
回调风格的第三方API可以通过Promise封装,把异步逻辑平铺在外层的async register函数里,避免嵌套回调,代码可读性更强。
可以用Node.js内置的util.promisify快速把nexmo.verify.request转成Promise风格,示例代码:
const util = require('util'); // 把回调风格的方法转成可await的Promise风格,绑定this避免上下文丢失 const verifyRequest = util.promisify(nexmo.verify.request).bind(nexmo.verify); exports.register = async (req, res) => { // 此处省略部分业务逻辑 try { // 直接await获取第三方API返回结果 const result = await verifyRequest({ number: formattedMobile, brand: "My Brand", code_length: "4", }); 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, }); await createdUser.save(); res.status(200).send({ user: createdUser._id, otp: requestId }); } catch (err) { // 统一处理第三方API错误、bcrypt错误、数据库保存错误 const errMsg = err.error_text || err; res.status(500).send(errMsg); } }
内容的提问来源于stack exchange,提问作者user8463989
相关产品推荐
相关产品推荐

