loadScript("/article/promise-chaining/one.js") .then(function(script) { returnloadScript("/article/promise-chaining/two.js"); }) .then(function(script) { returnloadScript("/article/promise-chaining/three.js"); }) .then(function(script) { // work on one two three });
window.addEventListener('unhandledrejection', function(event) { // the event object has two special properties: alert(event.promise); // [object Promise] - the promise that generated the error alert(event.reason); // Error: Whoops! - the unhandled error object });
new Promise(function() { throw new Error("Whoops!"); }); // no catch to handle the error
js+promise+cache example
1 2 3 4 5 6 7 8 9 10 11 12 13 14
function loadCached(url) { let cache = loadCached.cache || (loadCached.cache = new Map());
if (cache.has(url)) { return Promise.resolve(cache.get(url)); // (*) }
let urls = [ 'https://api.github.com/users/iliakan', 'https://api.github.com/users/remy', 'https://api.github.com/users/jeresig' ];
// map every url to the promise fetch(github url) let requests = urls.map(url => fetch(url));
// Promise.all waits until all jobs are resolved Promise.all(requests) .then(responses => responses.forEach( response => alert(`${response.url}: ${response.status}`) ));
let urls = [ 'https://api.github.com/users/iliakan', 'https://api.github.com/users/remy', 'https://api.github.com/users/jeresig' ];
// make fetch requests Promise.all(urls.map(url => fetch(url))) // map each response to response.json() .then(responses => Promise.all( responses.map(r => r.json()) )) // show name of each user .then(users => { // (*) for(let user of users) { alert(user.name); } });
改进
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
let urls = [ 'https://api.github.com/users/iliakan', '/', 'http://no-such-url' ];
Promise.all( urls.map(url => fetch(url).catch(err => err)) ) .then(responses => Promise.all( // if it's an error then pass on // otherwise response.json() and catch errors as results responses.map(r => r instanceof Error ? r : r.json().catch(err => err)) )) .then(results => { alert(results[0].name); // Ilya Kantor alert(results[1]); // SyntaxError: Unexpected token < in JSON at position 0 alert(results[2]); // TypeError: failed to fetch (text may vary) });