我的代码中有多个链式同步请求。我正在使用 NodeJS 包 request-promise。
这里有一些伪代码来展示它的格式:
initRequest.then(function(response){
return request2;
}).then(function(response2){
return request3;
}).then(function(response3){
return requestN;
}).catch(function(err){
log(error)
});
例如,如果 request3 失败,会发生什么?链是否继续,或者是否完全脱离循环?
如果request2是POST,而request3失败了,有没有办法系统地回滚request2更改的数据?
谢谢。
最佳答案
Does the chain continue, or does it break out of the loop completely?
它中断并继续catch
或finally
proposal ,它在最新的 Node.js 版本中可用,在旧版本中可使用 polyfillable - 类似于 try..catch..finally
对于同步代码的工作方式(这也是将普通 Promise 转换为 async
函数的方式)。
And if request2 was a POST, and request3 failed, is there a way to systematically roll back the data that request2 changed?
这应该由开发人员保护。如果数据有可能回滚,则应将必要的信息(数据条目 ID)保存到变量中并在 catch
中回滚。
关于node.js - 如何将交易系统构建成.then()链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50669896/