在 Promise.all 中一起调用承诺和非承诺

Calling a promise and a non-promise together in Promise.all

我有一个承诺,aPromise 调用服务器,还有一个非承诺,notAPromise,它被同步调用,我需要调用然后对结果做一些事情。我有这个但不确定这是否是最好的选择

Promise.all([aPromise(), Promise.method(notAPromise)()])
.spread(function(result1, result2) {
    //do something with results
})
.catch(function(error) {
    //do something with error
});

将同步notAPromise 放在Promise.all 中是正确的还是应该放在外面?

这种方式的好处是,如果 aPromise 需要一段时间从服务器返回,notAPromise 将在返回时完成。或者换句话说,我们不必等到同步 notAPromise 完成后再调用服务器。

有没有更好的方法来编写这段代码?

编辑: 此外,如果 notAPromise 正在更改某些状态,而不是返回结果,但我只想要新状态,如果 aPromise 也成功返回,那么可能会有问题。如果 aPromise 抛出但 notAPromise 已完成,我们将处于新状态,不是吗?

您的代码绝对没问题(甚至可以处理 notAPromise 将抛出的情况)。然而,通常一个人会简单地写

aPromise().then(function(result1) {
    var result2 = notAPromise();
    //do something with results
}).…

当我们不关心这两个函数的调用顺序或调用时间时。预计同步 notAPromise 需要的执行时间并不显着,如果它很重要(并且应该能够 运行 与其他东西并行)它应该是异步的。