Skip to content

Instantly share code, notes, and snippets.

@simondell
Last active November 2, 2016 17:43
Show Gist options
  • Save simondell/a6af8d9bb0fa2f29f80cee4af4ea4b59 to your computer and use it in GitHub Desktop.
Save simondell/a6af8d9bb0fa2f29f80cee4af4ea4b59 to your computer and use it in GitHub Desktop.
Getting a handle on JS Promises
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"); } );
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