Last active
August 29, 2015 14:24
-
-
Save sdevani/549069c1fcd71dd28fd4 to your computer and use it in GitHub Desktop.
Creating 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
// This is `promiseSetTimeout` which is a wrapper around `setTimeout` | |
// `promiseSetTimeout` manually builds out the `then` function to its result | |
// in order to demonstrate how promises work | |
var promiseSetTimeout = function(time) { | |
var result = {}; | |
var callbacks = []; | |
// `then` is a method that will take the callback and store | |
// it to be used later. In a promise-less world, this would | |
// be the callback function inserted in the call to `setTimeout`. | |
result.then = function(callback) { | |
callbacks.push(callback); | |
} | |
setTimeout(function() { | |
callbacks.forEach(function(cb) { | |
cb(); | |
}) | |
}, time); | |
return result; | |
} | |
// `promisify` takes a function that runs asynchronously via callbacks and | |
// returns a function that returns a promise | |
var promisify = function(func) { | |
// Create a function that will return a promise | |
// The input function takes two arguments with the 2nd one being | |
// a callback | |
var promiseFunc = function(arg1) { | |
// result will have 2 properties. Value (result of the async call), and | |
// `then` which is the promise-based function | |
var result = {}; | |
var callbacks = []; | |
func(arg1, function(value) { | |
// Execute all of the callbacks that were added to the callbacks array | |
result.value = value; | |
callbacks.forEach(function(cb) { | |
cb(value); | |
}); | |
}); | |
// Creation of the `then` function which will add a callback to | |
// our list | |
result.then = function(callback) { | |
callbacks.push(callback); | |
}; | |
return result; | |
}; | |
return promiseFunc; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment