【问题标题】:THEN statement returning with promise/always return and consistent-return bugsTHEN 语句返回承诺/总是返回和一致返回错误
【发布时间】:2019-02-19 20:35:06
【问题描述】:

这是我正在尝试部署的谷歌云功能的代码。我收到一个错误,说我的 .then() 承诺或不一致。有谁知道我做错了什么?

const admin = require('firebase-admin');
const twilio = require('./twilio');

module.exports = function(req, res) {
  if (!req.body.phone) {
    return res
      .status(422)
      .send({ error: 'You must provide a phone number' });
  }

  const phone = String(req.body.phone).replace(/[^\d]/g, '');

  admin
    .auth()
    .getUser(phone)
    .then(userRecord => {
      const code = Math.floor((Math.random() * 8999 + 1000));

      const message = {
        body: 'Your code is ' + code,
        to: phone,
        from: '+18053167032'
      };

      const callback = (err) => {
        if (err) {
          return res.status(422).send(err);
        }

        admin
          .database()
          .ref('users/' + phone)
          .update(
            { code: code, codeValid: true },
            () => { res.send({ success: true }
          );
      };

      twilio.messages.create(message, callback);
    })
    .catch((err) => {
      res.status(422).send({ error: err });
    });
}

【问题讨论】:

  • 仅供参考,您可以通过选择所有代码并使用编辑器中的 {} 按钮缩进整个代码来正确格式化代码。
  • 您能否编辑问题以准确显示您收到的错误?
  • 我已经使代码可读,部分原因是将参数分解为twilio.messages.create

标签: javascript firebase promise google-cloud-functions twilio-api


【解决方案1】:

在我的脑海中,你的缩进很难准确地使用花括号,并且作为对@hanoldaa 提到箭头函数的回应,能够准确跟踪 userRecord => 函数的位置非常重要结尾。如果它说你的 .then 承诺不一致,那么我会假设你要么在非承诺对象上调用 .then,要么你没有处理未解决的承诺。

Javascript.info 对未解决的承诺的全局处理有一个很好的建议,使用:

window.addEventListener('unhandledrejection', function(event) {
  // the event object has two special properties:
  alert(event.promise); // [object Promise] - the promise that generated the error
  alert(event.reason); // Error: Whoops! - the unhandled error object
});

new Promise(function() {
  throw new Error("Whoops!");
}); // no catch to handle the error

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    最后,你做到了

    .catch((err) => {
      res.status(422).send({ error: err });
    });
    

    err 不应该用括号括起来。使用

    .catch(err => {
      res.status(422).send({ error: err });
    });
    

    【讨论】:

    • 谢谢,这似乎解决了部分错误,但是在以 '.then(userRecord => ...'解决了吗?
    • 你可以尝试.then(function(userRecord) {,而不是箭头函数。
    • 仍然没有改善。还会创建一个警告,说明箭头回调的偏好
    • 你能解释为什么() “应该”被删除...?
    • 嗯,然后不确定错误。你能用stacktrace发布完整的错误吗?可能是截图。我的假设是不一致是抱怨声明箭头功能不同,但显然情况并非如此。对于单个参数,() 是可选的。
    猜你喜欢
    • 2016-03-09
    • 1970-01-01
    • 2016-02-28
    • 2021-01-04
    • 2015-11-27
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多