简体   繁体   中英

Node.JS recursive promise not resolving

i'm working with an API that allows me to sync data to a local DB. There is a syncReady API that I'm calling recursively until the sync batch is ready to start sending data. The recursion is working correctly and the .then callback is called, but the resolve function never resolves the response.

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);
            }
        );
    });
};

I get the 497 logged and the "The Response: {"pagesTotal";0}" response but the res(response) never sends the response down the chain. I've added a console.log message along the entire chain and none of the .then functions back down the chain are firing.

I hope I've explained this well enough :-). Any ideas why the promise isn't resolving?

Thanks!

First, you don't need to wrap something that returns a promise with a new Promise . Second, for your error case you don't resolve the promise if it is 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; } }) ); }; 

Maybe something like the above will work for you instead. Maybe try the above instead. As a general rule of thumb, it's you almost always want to return a Promise .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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