【问题标题】:Node.JS recursive promise not resolvingNode.JS 递归承诺无法解决
【发布时间】:2018-05-28 02:04:40
【问题描述】:

我正在使用允许我将数据同步到本地数据库的 API。我递归调用了一个syncReady API,直到同步批处理准备好开始发送数据。递归工作正常并调用了 .then 回调,但 resolve 函数从不解析响应。

const request = require('request-promise');
const config = require('../Configs/config.json');

function Sync(){}

Sync.prototype.syncReady = function (token, batchID) {
    return new Promise((res, rej) => {
        config.headers.Get.authorization = `bearer ${token}`;
        config.properties.SyncPrep.id = batchID;
        request({url: config.url.SyncReady, method: config.Method.Get, headers: config.headers.Get, qs: config.properties.SyncPrep})
            .then((response) => {
                console.log(`The Response: ${response}`);
                res(response);
            }, (error) => {
                console.log(error.statusCode);
                if(error.statusCode === 497){
                    this.syncReady(token, batchID);
                } else rej(error);
            }
        );
    });
};

我记录了 497 和“响应:{“pagesTotal”;0}”响应,但 res(response) 从未将响应发送到链中。我已经在整个链中添加了一条 console.log 消息,并且没有任何 .then 函数返回到链中。

我希望我已经解释得足够好:-)。任何想法为什么承诺没有解决?

谢谢!

【问题讨论】:

    标签: javascript node.js recursion promise


    【解决方案1】:

    首先,您不需要用new Promise 包装返回承诺的内容。其次,对于您的错误情况,如果它是497,则您不会解决承诺。

    const request = require('request-promise');
    const config = require('../Configs/config.json');
    
    function Sync(){}
    
    Sync.prototype.syncReady = function (token, batchID) {
          config.headers.Get.authorization = `bearer ${token}`;
          config.properties.SyncPrep.id = batchID;
          return request({url: config.url.SyncReady, method: config.Method.Get, headers: config.headers.Get, qs: config.properties.SyncPrep})
              .then((response) => {
                  console.log(`The Response: ${response}`);
                  return response;
              })
              .catch((error) => {
                  console.log(error.statusCode);
                  if(error.statusCode === 497){
                      return this.syncReady(token, batchID);
                  } else {
                      throw error;
                  }
              })
          );
    };

    也许像上面这样的东西对你有用。也许试试上面的方法。作为一般经验法则,您几乎总是希望返回Promise

    【讨论】:

    • 谢谢!解析 497 是解析链的关键。 res(this.syncReady(token, batchID));
    • 真的,我强烈建议不要将一个承诺包装在另一个承诺中,因为您需要做的就是返回承诺本身。
    猜你喜欢
    • 1970-01-01
    • 2018-05-29
    • 2016-12-23
    • 2015-12-08
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    相关资源
    最近更新 更多