Skip to main content

Posts

Showing posts with the label Promise

Javascript Promises

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...