Javascript Promises

• 4 min read

While explaining Promises to a friend I remembered reading a blog post couple of years back that explained the concept very well and made it all clear to me. However, I never bookmarked and searching for it, I can't find the specific post. Then I thought why not recreate some of the samples that the blog author had used to explain the concepts.

Here's what I came up with:

// Function to convert setTimeout into a Promise based // abstraction function delaySeconds(seconds) { return new Promise((resolve, reject) => { setTimeout(resolve, seconds*1000); }); } /* * A simple function that converts clunky setTimeout * callback based interface to a promise based * abstraction. */ function delayAndReturn(seconds, retval) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(retval); }, seconds*1000); }); } // example of how to use the above abstraction console.log("Calling delaySeconds with 10 seconds delay"); delaySeconds(10).then(() => { console.log("delaySeconds completed waiting 10 seconds"); }); // Function returns a Promise object that is rejected. function rejectPromise() { return new Promise((resolve, reject) => { reject(); }); } console.log("Calling delayAndReturn with 2 seconds timeout"); /* * This sample demonstrates: * - how to chain promises together * - returning values from an 'outer' Promise to an 'inner' * one * - return values can be any concrete datatype, including * another Promise instance. * - returning and handling errors/rejections */ delayAndReturn(2, 10).then(ret => { console.log("delayAndReturn - retval: ", ret); console.log("delayAndReturn, waiting 3 seconds"); return delaySeconds(3); }).then(() => { console.log("delayAndReturn -- second promise completion handler"); return 20; }).then((ret) => { console.log('delayAndReturn - final return value: ', ret, ', calling rejectPromise()..'); return rejectPromise(); }).then(() => { console.log('empty Promise completion handler'); console.log('First delaySeconds promise should complete in ~5 seconds'); }).catch(err => { console.log('delayAndReturn promise chain err: ', err); });

It's not nearly as complete as what's in the original post, but guess it ought to be enough to grasp the core concepts.