Created
May 11, 2016 15:09
-
-
Save zafarali/c77cee2a145cfa50f08bb6cd636893b9 to your computer and use it in GitHub Desktop.
how can we string together multiple promises especially those that have request()s in them?
This file contains hidden or 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
var q = require('q'); | |
var request = require('request'); | |
var context = { | |
query: 'hello how are you?' | |
} // global context to be mutated by all "plugins" | |
function hello_plugin(context){ | |
var query = context.query | |
var contains_hello = false; | |
query.split(' ').forEach(function(word){ | |
// console.log(word) | |
if(word === 'hello'){ | |
contains_hello = true; | |
} | |
}); | |
context['hello'] = contains_hello; | |
return context | |
} | |
function make_request(context){ | |
var deferred = q.defer() | |
if(context['hello']){ | |
request('http://www.google.com', function (error, response, body) { | |
if (!error && response.statusCode == 200) { | |
context['returned'] = true; | |
} | |
deferred.resolve(context) | |
}); | |
}else{ | |
deferred.resolve(context) | |
} | |
return deferred.promise | |
} | |
function not_important(context){ | |
if(context['hello'] && context['returned']){ | |
context['reply'] = 'hi there!' | |
} | |
return context | |
} | |
var promise_array = [hello_plugin, make_request, not_important]; | |
promise_array.reduce(q.when, q(context)).then(function(ctx){ | |
console.log(ctx); | |
}).catch(function(err){ | |
console.log(err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment