等待不等待解决承诺 [英] await not waiting to resolve promise

查看:63
本文介绍了等待不等待解决承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的小twilio函数/类返回的诺言,我确实将其导入到另一个文件中.我在这里得到 err res

This is my small twilio function/class returning promise which I do import in another file. I am getting err and res here returning it in promise

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

现在这是我正在使用的函数.

Now this is my function where I am using that function.

但是,当我执行 console.log(sendSms)时,即使在我从twilio函数返回promise的情况下,我也无法在控制台中对其进行定义.我在这里做错了.

But when I do console.log(sendSms) I get undefined in the console even I am returning promise from the twilio function. What I am doing wrong here.

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

请帮助!!!谢谢

推荐答案

您目前正在返回回调,可能不会返回 Promise -切换顺序,返回 Promise ,在 sendMessage 回调运行时解析.另请注意,如果存在 err ,则应该 reject ,如果没有,则应使用 res 进行 resolve .错误,而不是相反:

You're returning the callback at the moment, which probably doesn't return a Promise - switch the order around, return the Promise that resolves when the sendMessage callback runs. Also note that you should reject if there an err and resolve with the res if there is no err, not the other way around:

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

这篇关于等待不等待解决承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆