js-102
Version:
JS-102 helps you learn JavaScript (the right way) so that you can confidently use higher-level libraries and frameworks. — Let’s reveal the magic!
80 lines (59 loc) • 2.07 kB
JavaScript
/*
* the devil is in the details
* .--. __--__ (`-') .--. .----. .----.
* | ,|/ _ / ( OO).->/_ | / .. \\_,-. |
* |(_|\_..`--.(,------. | || / \ . .' .'
* ,--. | |.-._) \`------' | |' \ / '.' /_
* | '-' /\ / | | \ `' /| |
* `-----' `-----' `--' `---'' `------'
*
* This project is a part of the “Byte-Sized JavaScript” videocasts.
*
* You can watch “Byte-Sized JavaScript” at: https://bytesized.tv/
*
* MIT Licensed — See LICENSE.md
*
* Send your comments, suggestions, and feedback to me@volkan.io
*/
const util = require( '../lib/util' );
const separator = util.separator;
const log = console.log;
{
separator();
const underling = new Promise( ( resolve, reject ) => reject( 42 ) )
const overlord = underling.catch( ( reason ) => {
// This will result in `overlord` resolving with "hello".
//
// If you want to let this rejection cascade to `overlord`,
// that’s not how you do it (see the second example below for that).
return 'hello';
} );
overlord
.then( ( data ) => {
// Returning from the `cath` of the promise will let
// the owner promise `resolve` with the returned value:
log( `Resolved with “${data}”.` );
separator();
} )
.catch( ( reason ) => {
log( `Rejected with “${reason}”.` );
separator();
} );
}
{
const underling = new Promise( ( resolve, reject ) => reject( 42 ) )
const overlord = underling.catch(
( reason ) =>
// For the owner promise to `reject`, return a rejected promise:
Promise.reject( { reason, message: 'hello' } )
);
overlord
.then( ( data ) => {
log( `Resolved with “${data}”.` );
separator();
} )
.catch( ( reason ) => {
log( `Rejected with “${JSON.stringify(reason)}”.` );
separator();
} );
}