Javascript Promises
2018-11-05 THUDM team Eunbi Choi
- Syntax
new Promise( /* executor */ function(resolve, reject) { ... } );
executor:
A function that is passed with the arguments
resolve
andreject
. Theexecutor
function is executed immediately by the Promise implementation, passingresolve
andreject
functions (the executor is called before thePromise
constructor even returns the created object). Theresolve
andreject
functions, when called, resolve or reject the promise, respectively.
- 3 states
A
Promise
is in one of these states:- pending: initial state, neither fulfilled nor rejected.
- fulfilled: meaning that the operation completed successfully.
- rejected: meaning that the operation failed.
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. - 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()
andthrow new Error()
will cause the next catch() block to run. A catch() block also catches therunntime 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
https://medium.com/datafire-io/es6-promises-patterns-and-anti-patterns-bbb21a5d0918
原文地址:https://www.cnblogs.com/THUDM/p/9912352.html