2018-11-05 THUDM team Eunbi Choihtml
Syntaxes6
new Promise( /* executor */ function(resolve, reject) {
executor:api
A function that is passed with the arguments resolve
and reject
. The executor
function is executed immediately by the Promise implementation, passing resolve
and reject
functions (the executor is called before the Promise
constructor even returns the created object). The resolve
and reject
functions, when called, resolve or reject the promise, respectively. promise
3 statesapp
A Promise
ide
pending: initial state, neither fulfilled nor rejected.spa
fulfilled: meaning that the operation completed successfully.prototype
rejected: meaning that the operation failed.3d
A pending promise can either be fulfilled with a value, or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise's then
method are called. code
Chaining
As the Promise.prototype.then()
and Promise.prototype.catch()
methods return promises, they can be chained.
Methods
Promise.all(iterable)
Returns a promise that either fulfills when all of the promises in the iterable argument have fulfilled or rejects as soon as one of the promises in the iterable argument rejects.
example:
let filenames = ['index.html', 'blog.html', 'terms.html'];
Promise.all(filenames.map(readFilePromise))
.then(files => {
console.log('index:', files[0]);
console.log('blog:', files[1]);
console.log('terms:', files[2]);
});
Promise.race(interable)
Returns a promise that fulfills or rejects as soon as one of the promises in the iterable fulfills or rejects, with the value or reason from that promise.
example:
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(reject, ms);
});
}
Promise.race([readFilePromise('index.html'), timeout(1000)])
.then(data => console.log(data))
.catch(e => console.log("Timed out after 1 second"));
Promise.reject(reason)
Returns a Promise
object that is rejected with the given reason.
Promise.resolve(value)
Returns a Promise
object that is resolved with the given value.
Catching and throwing errors
We should consider all the code inside your then() statements as being inside of a try block. Both return Promise.reject()
and throw new Error()
will cause the next catch() block to run. A catch() block also catches the runntime error
inside then() statement.
Dynamic chains
Sometimes we want to construct our Promise chain dynamically.
example:
function readFileAndMaybeLock(filename, createLockFile) {
let promise = Promise.resolve();
if (createLockFile) {
promise = promise.then(_ => writeFilePromise(filename + '.lock', ''))
}
return promise.then(_ => readFilePromise(filename));
}
Running in series
Sometimes we want to run the Promises in series, or one after the other. There's no simple method in Promise, but Array.reduce can help us.
example:
let itemIDs = [1, 2, 3, 4, 5];
itemIDs.reduce((promise, itemID) => {
return promise.then(_ => api.deleteItem(itemID));
}, Promise.resolve());
same as:
Promise.resolve()
.then(_ => api.deleteItem(1))
.then(_ => api.deleteItem(2))
.then(_ => api.deleteItem(3))
.then(_ => api.deleteItem(4))
.then(_ => api.deleteItem(5));
Anti-patterns
Recreating callback hell
Failure to return
Calling .then() multiple times
Mixing callbacks and Promises
Not catching errors
references:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise