Node.JS递归承诺无法解析

时间:2017-12-14 03:51:06

标签: javascript node.js recursion promise

我正在使用一个允许我将数据同步到本地数据库的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(响应)从不在链中发送响应。我在整个链中添加了一个console.log消息,并且链中的.then函数都没有被触发。

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

谢谢!

1 个答案:

答案 0 :(得分:2)

首先,您不需要包含返回带有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