1

I have multiple chained, synchronous requests in my code. I am using the NodeJS package request-promise.

Here is some pseudocode to show how it is formatted:

initRequest.then(function(response){
    return request2;
}).then(function(response2){
    return request3;
}).then(function(response3){
    return requestN;
}).catch(function(err){
    log(error)
});

If, for example, request3 fails, what happens? Does the chain continue, or does it break out of the loop completely?

And if request2 was a POST, and request3 failed, is there a way to systematically roll back the data that request2 changed?

Thanks.

gkgkgkgk
  • 707
  • 2
  • 7
  • 26

2 Answers2

1

Does the chain continue, or does it break out of the loop completely?

It breaks and proceeds to catch or finally proposal, which is available in recent Node.js versions and polyfillable in older versions - similarly to how try..catch..finally works for synchronous code (this is how plain promises are translated to async functions as well).

And if request2 was a POST, and request3 failed, is there a way to systematically roll back the data that request2 changed?

This should be secured by a developer. If there's a possibility that data should be rolled back, necessary information (data entry ids) should be saved to variables and rolled back in catch.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • gotcha, thanks so much for the info. Rolling back could prove difficult, as there are potentially hundreds of POSTed objects that are being sent to a REST API. However I don't think it is as necessary as I initially thought. I am syncing info between two services, so if one service has only partially updated data, the rest would be flagged as not updated and would be picked up in the next sync process. Thanks again! – gkgkgkgk Jun 04 '18 at 02:11
1

if request3 fails, it will stop executing the rest of your request chains.

and there is no way to systematically rollback what request2 changed you would have to implement it your custom way.

to handle when request3 fails, catch request3 it self. here is a simple/mini way to handle when request3 fails

initRequest.then(function(response){
    return request2;
}).then(function(response2){
    return request3.catch(function(err2){
        //if something goes wrong do rollback
        request2Rollback.then(rollbackRes => {
            throw new Error("request3 failed! roll backed request 2!");
        }).catch(function(err){
            // the rollback itself has failed so do something serious here
            throw err;
        })
    });;
}).then(function(response3){
    return requestN;
}).catch(function(err){
    log(error)
});
miqe
  • 3,209
  • 2
  • 28
  • 36