I am having an issue with the order in which promises/functions get called. Basically I fetch an array of ID and then, for each id, want to fetch order detail and save. Then on to the next ID. As of now it will not save until every single order detail has been fetched.
The code:
// Convenience function
var fetchOrders = function() {
return self.fetchOrderList()
.then(function(orders) {
return P.map(orders, function(r) {
return self.fetchOrderById(r.id).then(fn);
});
});
};
// Fetch initial order list
var fetchOrderList = function() {
return new P(function(resolve, reject) {
debug('Fetching initial list');
resolve([{
id: 123
}, {
id: 134
}, {
id: 1333
}]);
});
};
var fetchOrderById = function(id) {
return new P(function(resolve, reject) {
debug('Fetching by ID');
resolve({
foo: 'bar'
});
}).then(function(o) {
debug('Saving');
return o;
})
};
fetchOrders();
Expected result:
Fetching initial list
Fetching by ID
Saving
Fetching by ID
Saving
Fetching by ID
Saving
Actual results
Fetching initial list
Fetching by ID
Fetching by ID
Fetching by ID
Saving
Saving
Saving