Skip to content

Instantly share code, notes, and snippets.

@gihrig
Created June 4, 2015 14:10
Show Gist options
  • Save gihrig/83510447e5d0bdbc0e91 to your computer and use it in GitHub Desktop.
Save gihrig/83510447e5d0bdbc0e91 to your computer and use it in GitHub Desktop.
Promises Ex1
/*
YDKJS Async and Performance ch 3:Promises "Chain Flow" pg 81
Generalized chain illustration, a delay-Promise creation
utility with error handling and substituted resolution message/
error recovery.
*/
'use strict';
function delay(time) {
// Wrap setTimeout in a promise, making it 'thenable'
// This technique can be applied to non-promise utilities
// such as an ajax() call.
return new Promise(function (resolve, reject) {
setTimeout(resolve, time);
});
}
// step 1:
console.log('step 1');
delay(0)
// step 2:
.then(function (response1) {
console.log('step 2 - error');
delay.bar(); // undefined, error!
// never gets here
return delay(100);
})
// step 3:
.then(
function fulfilled(response2) {
console.log('step 3 - fulfilled');
// never gets here
},
// rejection handler to catch the error
function rejected(err) {
console.log('step 3 - rejected');
console.log(err);
// `TypeError` from `delay.bar()` error reported
return 42; // recovery action
})
// step 4:
.then(function (msg) {
console.log('step 4 - recovered');
console.log(msg); // 42 - error recovered
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment