Ajay Srikanth
Ajay Srikanth

Reputation: 1185

Recursively call Promise

I've a method which makes post calls and on success it resolves a promise, but if the post calls fail for some reason I want to implement recursive logic to call the method that resolves the promise. How can I implement this to effectively handle the promises. Below is the code that i'm trying. Right now when the service call fails it is retrying but i'm getting unhandled rejection error and it is retrying again on it's own and then it is rejecting.

dummyService.getAction = (requestData) => {

    var options = {
        url: config.url,
        json: true,
        body: requestData,
        method: 'post',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'x-request-id': 'IntegrationTesting'
        }
    }

    return new Promise(function (resolve, reject) {
     request(options, function (error, response, body) {

            const success = new RegExp('^2\\d{2}$');
            const failure = new RegExp('^4\\d{2}$');

            if (error) {                
                reject(response);
            }
            else if (failure.test(response.statusCode) || recursive > 5) {                
                reject(response);
            }
            else if (success.test(response.statusCode) && body) {                
                resolve(body);
            }
            else {                
                recursive++;
                setTimeout(function () {
                    dummyService.getAction(requestData)
                }, 500);
            }
        })
    })
}

Upvotes: 1

Views: 136

Answers (1)

vadim
vadim

Reputation: 176

The problem is that the promise returned by dummyService.getAction when you're retrying is basically ignored. Try this:

setTimeout(function () {
    dummyService.getAction(requestData).then(resolve, reject);
}, 500);

Upvotes: 1

Related Questions