I am pretty new to the whole promises business and am trying out my project with them.
No I need to query an external API, go several items in the response, do other checks on my own database with them and when all of them are finished, need to resolve the whole promise in itself.
I also need even another call to my database at the marked point with another promise. These are independent from each other but the "parent" promise should only resolve when both are resolved.
I am at a wall here and probably need some general explanation about chaining several promises with multiple items.
Maybe I just understand something generally wrong here...
Here is my code so far (shortened at ...):
'use strict';
import rp from 'request-promise';
import _ from 'lodash';
var Import = {
init: function(user, options) {
return new Promise((resolve, reject) => {
rp.get("...") // call to external API
.then((res) => {
...
resolve();
});
...
});
},
run: function() {
return new Promise((resolve, reject) => {
...
rp.get(...) // call to external API
.then((res) => {
var events = JSON.parse(res).data;
var promises = [];
for (var i = 0; i < events.length; i++) {
promises.push(new Promise((resolve, reject) => {
...
Location.findOneAndUpdateAsync(...)
.then((loc) => {
events[i].location = loc._id;
resolve();
})
.catch((err) => {
console.error(err);
reject();
});
// I need even another call to my database here later with another promise
}));
}
return Promise.all(promises)
.then(() => {
console.log("all promises resolved");
resolve(events);
});
})
.catch((err) => {
console.error(err);
reject(err);
});
});
}
};