I have a scenario, where I have got an array of URL's that needs to be evaluated synchronously using request npm module. In details, Array will be forEach and it should bring data for current url and after then only move to pick next url. I am using yield generators. But It's not working. Please help guys!
var Promise = require("bluebird");
var request = Promise.promisify(require("request"), {multiArgs: true});
Promise.promisifyAll(request, {multiArgs: true})
var url_arr = ["https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=AIzaSyDe3MyoHI6aSbYKdHOXloz9QepAMfes9XE", "https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=AIzaSyDe3MyoHI6aSbYKdHOXloz9QepAMfes9XE"];
function* fetch(obj) {
console.log("2")
var myobj = yield request.getAsync(obj).promise();
console.log("3", myobj)
return myobj;
}
url_arr.forEach(function (obj){
console.log("1", obj)
var output = fetch(obj);
console.log("4, ", output);
});
In above snippet, Only 1 && 4 are printed in console. Two and three are never evaluated I think.
Remove return
statement from generator function, which suspends the generator, call .next()
to get the value
of the yield
ed object
function* _fetch(obj) {
var myobj = yield obj;
}
[1,2,3].forEach(function (obj) {
var {value:output} = _fetch(obj).next();
console.log("output:", output);
});