蓝鸟,承诺然后() [英] Bluebird, promises and then()
问题描述
我一直只使用蓝鸟几天,但我想查看我所有的旧代码和 promisify
它:)
I've been only using bluebird for a few days but I want to go over all my old code and promisify
it :)
我的问题是我仍然没有完全掌握然后()
命令的流程。
My problem is that I still don't fully grasp the flow of then()
commands.
考虑这两个块:
A
methodThatReturnsAPromise().then(task2).then(task3);
B
var promise = methodThatReturnsAPromise();
promise.then(task2)
promise.then(task3);
-
task3
会得到task2
的结果?在B中他们都得到了第一个承诺的结果?
in scenario A
task3
will get the result oftask2
? In B they all get the result of the first promise?
第二个与蓝鸟运行 Promise.all
有什么不同?
How does the second one differ from running Promise.all
from bluebird?
在使用 catch时,这些A / B /
方法(我在哪里放)。 Promise.all
有何不同
How do these A/B/Promise.all
differ when it comes to using the catch
method (where do I put it).
对不起,这是一堆问题一个。
Sorry it's a bunch of questions in one.
推荐答案
欢迎来到美好的承诺世界。
Welcome to the wonderful world of promises.
您的断言在 1
是对的。我们可以使用 Promise.resolve
模拟一个在Bluebird中解析的promise。
Your assertion in 1
is correct. We can simulate a promise resolving in Bluebird using Promise.resolve
on a value.
让我们看看:
让我们得到一个返回承诺的函数:
Let's get a function that returns a promise:
function foo(){
return Promise.resolve("Value");
}
foo().then(alert);
这个简短的片段会提醒价值
如我们可以看到。
This short snippet will alert "Value"
as we can see.
现在,让我们创建两个承诺,每个承诺提醒并返回不同的值。
Now, let's create two more promises, each that alert and return different values.
function task2(e){
alert("In two got " + e);
return " Two ";
}
function task3(e){
alert("In three got " + e);
return " Three ";
}
所以,你可以在你的第一个代码它确实会在链中解析,每个代码都包含前一部分的值。
So, as you can see in your first code it will indeed resolve in a chain, each with the value of the previous part.
在第二个示例中,task2和task3将获得相同的值并且也将一起执行(即,任务3不会等待任务2)。你可以看到这里。
In the second example, both task2 and task3 will get the same value and will also execute together (that is, task 3 will not wait for task 2). You can see that here.
Promise.all(或者只是从然后
履行处理程序返回一个数组,然后使用 .spread
)用于等待多个结果全部完成。在您的示例中,您将在多个部分中连接单个结果。
Promise.all (or just returning an array from a then
fulfillment handler and then using .spread
) is used for waiting for multiple results to all complete. On your example, you're hooking on a single result in multiple parts.
您始终把catch放在你想要捕获错误的位置。正如你通常在同步代码中那样。只记得总是投入承诺或承诺的代码。
You always put catch where you want the error to be caught. As you would normally in synchronous code. Just remember to always throw in a promise or in promisified code.
这篇关于蓝鸟,承诺然后()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!