Skip to content

Instantly share code, notes, and snippets.

@AmrAbdulrahman
Last active January 25, 2016 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmrAbdulrahman/950cf46a25685d6b1e7a to your computer and use it in GitHub Desktop.
Save AmrAbdulrahman/950cf46a25685d6b1e7a to your computer and use it in GitHub Desktop.
function asyncSayHiTo(name) {
// define a defer
// defer is the context of the ASYNC operation
var defer = q.defer();
// make an async operation
setTimeout(function() {
// this should run after the function already terminated
// and returned a promise
if (name !== undefined) {
var hiMsg = 'Hi ' + name + '!';
// now we're keeping our promises and telling whoever holds the promise
// "Here you go! I'm done with my ASYNC stuff, and this is my output"
// note that we don't care which function is listening to this promise,
// and to whom exactly we're sending this output ... encapsulation!
// we do what we're supposed to do, and nothing more.
// equivalent to successCallback() we call .resolve()
defer.resolve(hiMsg);
} else {
// something wrong, we gave a promise, and we need to keep it
// but we can't pretend that everything is okay
// equivalent to failureCallback() we call .reject()
defer.reject('Come on! you need to give a name!');
}
}, 2000);
// return a promise that we will give you a response after sometime
// note that the following code executes before the callback
// of setTimeout() executes
return defer.promise;
}
// call an async operation
asyncSayHiTo('Amr')
// .then() is just the beautiful part, makes code much more readable
// and self descriptive, .then() comes after async operation.
.then(function result(hiMsg) {
console.log(hiMsg); // logs: "Hi Amr!"
});
// invalid call to an async operation
// it's invalid because we should pass it a 'name' argument
asyncSayHiTo()
.then(function result(hiMsg) {
console.log(hiMsg);
}, function error(reason) {
console.log('Oh! Something went wrong: ' + reason);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment