我已经编写了一个promise.all
函数,如下所示,它没有返回我预期的结果。
if (Array.isArray(data)) {
return Promise.all(data.map((data) => {
hook.app.service('location')
.find({ query: { serviceLocationId:"100" } })
.then((result) => {
var startDept = result.data[0];
if (result.data.length > 0) {
data.problem.solutions.solution.routes.route.forEach((d) => {
d.stops.unshift({
serviceType: '',
orders: [],
travelTime:'',
travelDistance:'',
travelCost:'',
serviceTime: '',
serviceTimeCost:0,
tripNumber:0,
stopName : startDept.description,
arrivalTime:'',
departureTime : 36000.0,
locationType : startDept.locationType,
sequence : 0,
locationId : startDept.serviceLocationId,
lng : startDept.location.lng,
lat : startDept.location.lat
});
var endDept = d.stops.pop();
d.stops.push({
serviceType: '',
orders: [],
travelTime:endDept.travelTime,
travelDistance:endDept.travelDistance,
travelCost:endDept.travelCost,
serviceTime: '',
serviceTimeCost:0,
tripNumber:0,
stopName : startDept.description,
arrivalTime : endDept.arrivalTime,
departureTime:'',
locationType : startDept.locationType,
sequence : endDept.sequence,
locationId : endDept.locationId,
lng : startDept.location.lng,
lat : startDept.location.lat
});
});
hook.data = data;
combineArr = [];
return routes(hook).then((hook) => {
if ([hook.data].length > 0) {
combineArr.push(hook.data);
return combineArr;
} else {
next(new Error('routes response create failed'));
}
}).catch((err) => { return next(new Error(err.error)); });
} else {
next(new Error('no depo found'));
}
}).catch(err=>{ return next(new Error(err.error)); });
})).then((results) => {
console.log(results);
hook.result = results;
next();
});
}
上述承诺返回[null, null]
.我没有得到预期的结果。请帮助我解决这个问题。
你没有从map
回调返回任何内容,所以生成的数组是一个undefined
数组,而不是 promise。您需要返回在回调中得到的承诺,因此数组是承诺数组。
基本上,您正在这样做:
return Promise.all(myArray.map(entry => {
getAPromise(entry);
}));
。你应该在哪里做
return Promise.all(myArray.map(entry => {
return getAPromise(entry);
}));
....或
return Promise.all(myArray.map(entry => getAPromise(entry)));