Promise is a very simple concept. Even if you have no chance to use it, you probably know it. Promise is a very valuable constructor that helps you to assemble asynchronous code in a more readable way instead of using an embedded anonymous method. Here we will introduce the six simplest features. We hope this will help you to look at Javascript Promise before we start the official introduction:
The Code is as follows:
Var p = new Promise (function (resolve, reject ){
Resolve ("hello world ");
});
P. then (function (str ){
Alert (str );
});
1. then () returns a Forked Promise
What are the differences between the following two sections of code?
The Code is as follows:
// Exhibit
Var p = new Promise (/*...*/);
P. then (func1 );
P. then (func2 );
// Exhibit B
Var p = new Promise (/*...*/);
P. then (func1)
. Then (func2 );
If the above two sections of code are the same, then Promises is just a one-dimensional callback function array. However, this is not the case. Each then () call returns a forked promise. Therefore, in ExhibitA, if func1 () throws an exception, func2 () is still called normally.
In ExhibitB, if func1 () throws an error, fun2 () will not be called, because the first call returns a new promise, which is in func1 () is rejected. The result is that func2 () is skipped.
Summary: promises can be fork into multiple paths, similar to complex flowcharts.
2. Callback should pass the result
When you run the following code, what will you receive a warning?
The Code is as follows:
Var p = new Promise (function (resolve, reject ){
Resolve ("hello world ");
});
P. then (function (str ){})
. Then (function (str ){
Alert (str );
});
The alert in the second then () does not display any content. This is because the callback function is in the context of promise, because the result changes, there is no callback function. Promise expects your callback function to return the same result or return a replacement result, and then be passed to the next Callback Function.
The result is similar to the following:
The Code is as follows:
Var feetToMetres = function (ft) {return ft * 12*0.0254 };
Var p = new Promise (/*...*/);
P. then (feetToMetres)
. Then (function (metres ){
Alert (metres );
});
3. Only exceptions from the previous layer can be captured.
What are the differences between the two codes?
The Code is as follows:
// Exhibit
New Promise (function (resolve, reject ){
Resolve ("hello world ");
})
. Then (
Function (str ){
Throw new Error ("uh oh ");
},
Undefined
)
. Then (
Undefined,
Function (error ){
Alert (error );
}
);
// Exhibit B
New Promise (function (resolve, reject ){
Resolve ("hello world ");
})
. Then (
Function (str ){
Throw new Error ("uh oh ");
},
Function (error ){
Alert (error );
}
);
In the first code, an exception in the first then () is thrown and will be captured by the second then (). then, the "uh oh" warning will be triggered. Only exceptions at the previous level will be caught.
In the second code, the callback function and the error callback function are at the same level, meaning that exceptions are not caught when they are thrown in the callback. In fact, the error callback of the second part of the code will only be thrown if promise is rejected or the promise itself has an error.
4. errors can be recovered
In an error callback function, if you do not throw an error again, promise assumes that you have recovered from the error and reversed it to the resolved status. In the next example, "I'm saved" will be displayed because the error callback in the first then () does not throw an exception again.
The Code is as follows:
Var p = new Promise (function (resolve, reject ){
Reject (new Error ("pebkac "));
});
P. then (
Undefined,
Function (error ){}
)
. Then (
Function (str ){
Alert ("I am saved! ");
},
Function (error ){
Alert ("Bad computer! ");
}
);
Promise can be seen as a layer on an onion. Add another layer to the onion for each then. Each layer represents a processed activity. When the hierarchy ends, the results are considered fixed and ready for the next hierarchy.
5. The Promises can be paused.
Because you are ready to execute in a then () method, it does not mean that you cannot pause and run other tasks in advance. To pause the current promise or wait for another promise to complete, return another promise in then.
The Code is as follows:
Var p = new Promise (/*...*/);
P. then (function (str ){
If (! LoggedIn ){
Return new Promise (/*...*/);
}
})
. Then (function (str ){
Alert ("Done .");
})
In the previous code, the prompt will not appear until the new promise is parsed. This is a convenient way to introduce more dependencies in an existing asynchronous code path. For example, you may find that the user session has timed out, and you may want to initialize the second login before continuing the previous code path.
6. Resolved Promises will not be executed immediately
Will the prompt box be displayed when running the following code?
The Code is as follows:
Function runme (){
Var I = 0;
New Promise (function (resolve ){
Resolve ();
})
. Then (function (){
I + = 2;
});
Alert (I );
}
Because promise is parsed immediately and the then () method is executed immediately, you may think that prompt 2 will be displayed. However, the promise definition requires that all calls be forced asynchronous. The prompt is generated before the modification.