我一直只使用蓝鸟几天,但我想查看所有旧代码和promisify
它:)
我的问题是我仍然没有完全掌握then()
命令的流程。
考虑以下两个方块:
A
methodThatReturnsAPromise().then(task2).then(task3);
乙
var promise = methodThatReturnsAPromise();
promise.then(task2)
promise.then(task3);
task3
中的会得到task2
的结果吗?在B中他们都得到了第一个承诺的结果?
第二个与蓝鸟运行Promise.all
有什么不同?
在使用Promise.all
方法时,这些A / B / catch
如何不同(我在哪里放)。
对不起,这是一堆问题。
答案 0 :(得分:48)
欢迎来到美好的承诺世界。
then
如何在您的示例中运作您在1
中的断言是正确的。我们可以使用Promise.resolve
模拟一个在Bluebird中解析的promise。
让我们看看:
让我们得到一个返回承诺的函数:
function foo(){
return Promise.resolve("Value");
}
foo().then(alert);
此简短代码段会将"Value"
警告为we can see。
现在,让我们创建两个承诺,每个承诺都会发出警报并返回不同的值。
function task2(e){
alert("In two got " + e);
return " Two ";
}
function task3(e){
alert("In three got " + e);
return " Three ";
}
所以,正如你在your first code中看到的那样,它确实会在链中解析,每个链都具有前一部分的值。
在第二个示例中,task2和task3将获得相同的值并且也将一起执行(即,任务3不会等待任务2)。您可以看到here。
Promise.all(或只是从then
履行处理程序返回一个数组,然后使用.spread
)用于等待多个结果全部完成。在您的示例中,您将在多个部分中连接单个结果。
您始终将catch放在您希望捕获错误的位置。正如你通常在同步代码中那样。只记得总是投入承诺或承诺的代码。
答案 1 :(得分:12)
方案中的任务3会得到task2的结果吗?在B中他们都得到了第一个承诺的结果?
是
第二个与蓝鸟运行Promise.all有什么不同?
您不会将(并行)任务2和3的结果提取到新的承诺中。
这些A / B / Promise.all在使用catch方法时有何不同(我在哪里放)。
通常你会把它放在链的末尾,除非你想捕捉一个特定的错误。
promise.catch()
// handles rejections of this promise
promise.then(task2).catch()
// handles rejections from either promise or task2
// if promise is rejected, task2 will not be executed
Promise.all(promise.then(task2), promise.then(task3)).catch()
// handles rejections from any.
// if promise is rejected, neither task2 nor task3 will be executed
// if task2 or task3 throw, the error will immediately handled
// and the other task will not be affected (but its result is unavailable)
答案 2 :(得分:3)
你没有得到一个简单的原则链接
在第一个可以写成像
var promise = methodThatReturnsAPromise(), promise1 = promise.then(task2); promise1.then(task3);
在第二种情况下
var promise = methodThatReturnsAPromise(); promise.then(task2) promise.then(task3);
希望这能解释两者的差异