Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

javascript - Bluebird, promises and then()

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.

Consider these two blocks:

A

methodThatReturnsAPromise().then(task2).then(task3);

B

var promise = methodThatReturnsAPromise();
promise.then(task2)
promise.then(task3);
  1. in scenario A task3 will get the result of task2? In B they all get the result of the first promise?

  2. How does the second one differ from running Promise.all from bluebird?

  3. 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.

question from:https://stackoverflow.com/questions/21298190/bluebird-promises-and-then

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Welcome to the wonderful world of promises.

How then works in your example

Your assertion in 1 is correct. We can simulate a promise resolving in Bluebird using Promise.resolve on a value.

Let's show this:

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.

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

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.

The 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...