Last active
November 2, 2016 17:43
-
-
Save simondell/a6af8d9bb0fa2f29f80cee4af4ea4b59 to your computer and use it in GitHub Desktop.
Getting a handle on JS Promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function timedPromise ( t, label ) { | |
console.info( 'making promise for ' + label ); | |
return ( res,rej ) => { | |
setTimeout( () => { | |
console.log( label ); | |
res( label ) | |
}, t ); | |
} | |
} | |
function makePromise (fulfil) { | |
let p = new Promise( timedPromise( 1000, 'first' ) ); | |
if( fulfil ) { | |
console.log('will resolve'); | |
p.then( value => { new Promise( timedPromise( 100, `after ${value}[0]` ) ) } ); | |
p.then( value => { new Promise( timedPromise( 100, `after ${value}[1]` ) ) } ); | |
return p; | |
} else { | |
console.log('will reject'); | |
return Promise.resolve(null); | |
} | |
} | |
makePromise(true).then( function () { console.log("after true"); return 'after' } ).then( ( val ) => new Promise ( timedPromise( 100, `${val} after true` ) ) ); | |
// makePromise(false).then( function () { console.log("after false"); } ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function firstAsync ( shouldError ) { | |
return new Promise( function ( res, rej ) { | |
if( shouldError ) rej( 'error' ); | |
else res( 'no error' ); | |
}); | |
} | |
function activate ( message ) { | |
console.log( `activate with ${message}` ); | |
return new Promise( function ( res, rej ) { | |
console.log( `second promise with ${message}` ); | |
}); | |
} | |
firstAsync(false) | |
.then( () => 'first passed', (ex) => `first rejected with ${ex}` ) | |
.then( activate ) | |
.then( undefined, (ex) => { console.error( ex ); } ); | |
firstAsync(true) | |
.then( () => 'first passed', (ex) => `first rejected with ${ex}` ) | |
.then( activate ) | |
.then( undefined, (ex) => { console.error( ex ); } ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment