Dar*_*ght 0 javascript asynchronous node.js async-await
这是我的小twilio函数/类返回promise,我在另一个文件中导入.我得到了,err并res在这里以承诺回报它
class TwilioService {
sendSms(to, message) {
return this.twilio.sendMessage(sms,(err,res) => {
return new Promise((resolve, reject) => {
if (err) {
console.log(err)
return resolve(res)
} else {
console.log(res, 'ppppppppppppppppp')
return reject(res)
}
})
})
}
}
Run Code Online (Sandbox Code Playgroud)
现在这是我使用该功能的功能.
但是当我这样做时,我console.log(sendSms)在控制台中得到了未定义,即使我从twilio函数返回了promise.我在这做错了什么.
import Twilio from '../../services/twilio'
const twilio = new Twilio()
const handler = async(request, reply) => {
try {
const sendSms = await twilio.sendSms(`+91${mobile}`, `Welcome to App. User ${verificationCode} as your signup OTP.`)
console.log(sendSms, 'oooooooooooooooo')
} catch(err) {
console.log(err)
}
}
Run Code Online (Sandbox Code Playgroud)
请帮忙!!!谢谢
你现在正在返回回调,这可能不会返回Promise- 切换顺序,返回Promise在sendMessage回调运行时解析的.还要注意的是,你应该reject,如果有一个err,并resolve与res如果没有err,而不是其他方式:
class TwilioService {
sendSms(to, message) {
return new Promise((resolve, reject) => { // switch these two lines
return this.twilio.sendMessage(sms, (err, res) => { // switch these two lines
if (err) {
console.log(err)
return reject(res) // reject on error, don't resolve
} else {
console.log(res, 'ppppppppppppppppp')
return resolve(res) // resolve when there's no error
}
})
})
}
}
Run Code Online (Sandbox Code Playgroud)