繁体   English   中英

Node.JS递归承诺未解决

[英]Node.JS recursive promise not resolving

我正在使用一个API,该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日志和“ The Response:{“ pagesTotal”; 0}“响应,但是res(response)从未沿链发送响应。 我在整个链中添加了console.log消息,链中的.then函数均未触发。

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

谢谢!

首先,您不需要使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM