2. Promise
The Promise object is used for deferred and asynchronous computations. A
Promise represents an operation that hasn't completed yet, but is expected in
the future.
Syntax
new Promise(executor);
new Promise(function(resolve, reject) { ... });
Parameters
executor
Function object with two arguments resolve and reject. The first argument
fulfills the promise, the second argument rejects it. We can call these functions
once our operation is completed.
3. Promise
A Promise is in one of these states:
pending: initial state, not fulfilled or rejected.
fulfilled: meaning that the operation completed successfully.
rejected: meaning that the operation failed.
4. Promise
Pending、Resolved(Fulfilled)、Rejected。
var promise = new Promise(function(resolve, reject)
{
// ... some code
if (/* asyc success*/){
resolve(value);
}
else { reject(error); }
});
resolve函數的作用是,將Promise對象的狀態從「未完成」變為「成功」(即從Pending變為
Resolved)
reject函數的作用是,將Promise對象的狀態從「未完成」變為「失敗」(即從Pending變為
Rejected)
5. Promise - then
The then() method returns a Promise. It takes two arguments, both are
callback functions for the success and failure cases of the Promise.
Syntax:
p.then(onFulfilled, onRejected);
p.then(function(value) {
// fulfillment
}, function(reason) {
// rejection
});
13. var promise = new Promise(function(resolve, reject) {
throw new Error('test')
});
promise.catch(function(error) {
console.log(error); // Error: test
});
14. var promise = new Promise(function(resolve, reject) {
resolve("ok");
throw new Error('test');
});
promise.then(function(value) { console.log(value) })
.catch(function(error) { console.log(error) });
//Output: ok
15. Promise.all()
The Promise.all(iterable) method returns a promise that resolves when all of
the promises in the iterable argument have resolved.
Syntax
Promise.all(iterable);
Parameters
Iterable : An iterable object, such as an Array…
EX.
var p = Promise.all([p1,p2,p3]);
17. Promise.race()
The Promise.race(iterable) method returns a promise that resolves or
rejects as soon as one of the promises in the iterable resolves or
rejects, with the value or reason from that promise.
Syntax
Promise.race(iterable);
EX.
var p = Promise.race([p1,p2,p3]);
18. Promise.resolve()
The Promise.reject(reason) method returns a Promise object that is
rejected with the given reason.
Syntax
Promise.reject(reason);
Parameters
reason
Reason why this Promise rejected.
var p = Promise.resolve();
p.then(function () { // ... });
19. Promise.resolve()
var jsPromise = Promise.resolve($.ajax('/whatever.json'));
var p = Promise.resolve('Hello');
p.then(function (s){ console.log(s)});
// Hello
20. Promise.reject()
var p = Promise.reject('出錯了');
p.then(null, function (s){ console.log(s)}); // 出錯了