我写了一个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]
。我没有得到预期的结果。请帮我解决这个问题。
答案 0 :(得分:2)
您没有从map
回调中返回任何内容,因此生成的数组是undefined
的数组,而非承诺。您需要返回您在回调中获得的承诺,以便数组是一组承诺。
基本上,你是这样做的:
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)));