用嵌套的Promises编写干净的代码 [英] Writing Clean Code With Nested Promises

查看:49
本文介绍了用嵌套的Promises编写干净的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个与Apple通话以验证收据的应用。它们都有一个可以发布到的沙箱和生产网址。

I'm writing an app that talks to Apple to verifyReceipts. They have both a sandbox and production url that you can post to.

与Apple通信时,如果您收到21007状态,则表示您要发布到生产网址,当你应该发布到沙箱中时。

When communicating with Apple, if you receive a 21007 status, it means you were posting to the production url, when you should be posting to the sandbox one.

所以我写了一些代码来促进重试逻辑。这是我的代码的简化版本:

So I wrote some code to facilitate the retry logic. Here's a simplified version of my code:

var request = require('request')
  , Q = require('q')
  ;

var postToService = function(data, url) {
  var deferred = Q.defer();
  var options = {
    data: data,
    url: url
  };

  request.post(options, function(err, response, body) {
    if (err) { 
      deferred.reject(err);
    } else if (hasErrors(response)) {
      deferred.reject(response);
    } else {
      deferred.resolve(body);
    }
  });

  return deferred.promise;
};

exports.verify = function(data) {
  var deferred = Q.defer();

  postToService(data, "https://production-url.com")
    .then(function(body) {
      deferred.resolve(body);
    })
    .fail(function(err) {
      if (err.code === 21007) {
        postToService(data, "https://sandbox-url.com")
          .then(function(body){
            deferred.resolve(body);
          })
          .fail(function(err) {
            deferred.reject(err);
          });
      } else {
        deferred.reject(err);
      }

    });

  return deferred.promise;
};

验证函数中的重试部分非常丑陋,难以用嵌套的promises读取。有没有更好的方法呢?

The retry portion in the verify function is pretty ugly and difficult to read with the nested promises. Is there a better way of doing this?

推荐答案

您可以在拒绝处理程序中重新抛出错误以继续拒绝承诺,或者你可以返回一个新的承诺来取代拒绝。

You can re-throw an error in the rejection handler to continue rejecting the promise, or you can return a new promise to replace the rejection.

exports.verify = function(data) {
  return postToService(data, "https://production-url.com")
    .fail(function(err) {
      if (err.code === 21007) {
        return postToService(data, "https://sandbox-url.com")
      } else {
        throw err
      }
    });
};

这篇关于用嵌套的Promises编写干净的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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