using bluebird how can i do the following work.
groupCast = [Promise.resolve("name1"), Promise.resolve("name2"),Promise.resolve("name3")]
Promise.map( groupCast , function (group){
Promise.resolve($http.get("/getdata" , params:{group:group}))
.then(function(response){ console.log(group," done")return response}))
return response
})
.then(function(resp){console.log(resp)})
if the response for each group for the http call was "one" , "two" , "three" We would then expect to have:
"name1 done";
"name2 done";
"name3 done";
[ "one" , "two" ,"three" ]
However i get
[ "one" , "two" ,"three" ]
"name1 done";
"name2 done";
"name3 done";
How could I fix it. i cannot use async and wait because its not supported by IE.
First off, your code formatting makes it a bit hard to see what's going on. Let me clean it up a bit and add some comments so you can see what's happening.
Promise.map(groupCast, function(group) {
//the following kicks off a new promise, which is not chained to the current one
Promise.resolve($http.get("/getdata", { params: { group: group } })).then(
function(response) {
console.log(group, " done");
//you're returning response below, but it's not going anywhere!
return response;
}
);
//The current promise resolves right away, not waiting for the $http call.
//Also, you're returning an undefined value here.
return response;
}).then(function(resp) {
//the prior promise resolves with undefined.
console.log(resp);
});
Now let's fix it so the promises chain properly.
Promise.map(groupCast, function(group) {
// $http.get returns a promise already. No need to wrap it in one.
// Also, let's go ahead and return the chained promise so the `map` function can wait for it.
return $http.get("/getdata", { params: { group: group } })
.then(function(response) {
console.log(group, " done");
return response;
});
}).then(function(resp) {
//the prior promise should now resolve as expected.
console.log(resp);
});