Promise:当抛出错误时,其他异步请求会发生什么?

Promise: What happens to other async request when errors are thrown?

我正在使用 Bluebird promise。这在文档中并不是很明确。假设如下,假设所有实例都是适当的承诺:

FindSomeDBModel.then(function(model) {
    return [
        model.getOtherModels(),
        aHTTPRequest('https://google.com')
    ];
}).spread(function(otherModels, httpResponse) {
    // some code
}).catch(function(err) {
    res.status(500).send(err);
});
  1. 如果model.getOtherModelsaHTTPRequest都抛出错误,catch中的err变量会是什么?

  2. 此外,如果 model.getOtherModels 首先抛出错误,它会导致向客户端发送响应还是等待 aHTTPRequest 完成?随后,aHTTPRequest抛出,然后会发生什么?

  3. 我可以在其中一个请求抛出错误时立即响应客户端吗?因为不再是material对方响应是否完成并成功

如果这两个 promise 执行中的一个发生错误,将会发生什么

  • 在您的 catch 回调中收到错误
  • 另一个承诺不受影响,继续执行
  • 您给 spread 的回调没有被调用

如果model.getOtherModelsaHTTPRequest都抛出错误,只有第一个会被catch接收到,另一个将被忽略。

你给catch的回调会被尽快调用,当第一个错误被抛出时,你的代码不会等待另一个错误的执行。

If both model.getOtherModels and aHTTPRequest throws an error, what will be inside the err variable in the catch?

AggregateError 本来是最佳的,但由于与 .all 的兼容性,它在 Bluebird 之外指定,而 bluebird 兼容 - 它将首先解决 拒绝上链。

在它自己的方法中不需要ES6兼容性bluebird会return所有错误。

Also, what if model.getOtherModels throws an error first, will it cause a response to be sent out to the client or will it wait for aHTTPRequest to complete? Subsequently, aHTTPRequest throws, then what happens?

一旦抛出错误就会拒绝(并立即输入catch),bluebird有一个特例.spread它会检查传递的参数是否为数组并调用.all 就可以了 - 这是一个特例,如果你 .thend 而不是 .spreading 它就不会发生。

Can I respond back to the client as soon as one of the request throws an error? Because it is no longer material whether the other response completes and succeeds.

是的,但考虑使用类型化(或谓词)异常来进行更有意义的错误处理 - 如果发生了不是 OperationalError 的错误,您可能需要重新启动服务器。