Размещенный код отредактирован, поэтому сложно точно показать, как его реорганизовать, но есть обязательные и рекомендуемые изменения.
Рекомендуемое изменение - обещать router.get()
. Глядя на это первым ...
// get the xxx route. return a promse that resolves to the get response
// TODO: error handling
function getXXX() {
return new Promise(function(resolve, reject) {
router.get('/xxxx', function(req, res){
resolve(res);
});
});
}
Называя это ...
function theOPFunction() {
return getXXX().then(function(res) {
return _DB_Knex('xxx')
.where({ "xxxx": "xxxx" })
.select('xxxx.*', 'xxx.xxx as xxx', 'xxx.xxxx')
.leftJoin('xxxx', 'xxx.xxx', 'xxx.xxx')
}).then(function(data) {
return loopAndGatherPromises(data); // see below
})
}
Требуемое изменение состоит в том, что цикл через data
должен собрать производимые в нем обещания и запустить их с Promise.all()
.
function loopAndGatherPromises(data) {
let promises = [];
if(data && data.length>0){
for(var i=0; i<data.length; i++){
if(xxxxx){
var xxx = xxxxx;
var xxx = data[i].xxxx;
var xxx = data[i].xxxx;
var xxx = data[i].xxx;
if(xxx>=xxx){
promises.push(updateAndPost(data));
}
}
}
}
return Promise.all(promises);
}
// updateAndPost answers a chain of three promises update the db and
// post to two web services. note these 3 chained promises probably
// could be made parallel with promise.all
function updateAndPost(data) {
return _DB_Knex('xxxx').where({xxx: "xxxx",xxx: xxxx}).update({ xxxx : "xxxx"}).then(function(){
return request.post({
url: `${api_url}/xxxxx/s`,
body: { xxx: xxxx },
json: true
});
}).then(function() {
return request.post({
url: `${api_url}/xxxxx/xxxx`,
body: { xxx: xxxx },
json: true
});
});
}