I am using promise function like this:
// WORK
let res = {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc};
for (let i = 0; i < rv.copyDetailList.length; i ++) {
const item = rv.copyDetailList[i];
const v = await convertCommonInfo(item);
if (!item.errorId) {
res.approveList.push(v);
} else {
res.rejectList.push(merge(v, {errorId: item.errorId, errorDesc: item.errorMsg}));
}
}
This works well, but I want to try to use some functional function, I find that I have to use map
then reduce
// WORK, But with two traversal
const dataList = await promise.all(rv.copyDetailList.map((item) => convertCommonInfo(item)));
const res = dataList.reduce((obj, v, i) => {
const item = rv.copyDetailList[i];
if (!item.errorId) {
obj.approveList.push(v);
} else {
obj.rejectList.push(merge(v, {errorId: item.errorId, errorDesc: item.errorMsg}));
}
return obj;
}, {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc});
I find that forEach
function can not work:
// NOT WORK, not wait async function
rv.copyDetailList.forEach(async function(item) {
const v = await convertCommonInfo(item);
if (!item.errorId) {
res.approveList.push(v);
} else {
res.rejectList.push(merge(v, {errorId: item.errorId, errorDesc: item.errorMsg}));
}
});
This doesn't work, it just return init value. In fact this puzzle me, sine I await
the function, why not work?
Even I want to use reduce
function:
// NOT WORK, Typescirpt can not compile
rv.copyDetailList.reduce(async function(prev, item) {
const v = await convertCommonInfo(item);
if (!item.errorId) {
prev.approveList.push(v);
} else {
prev.rejectList.push(merge(v, {errorId: item.errorId, errorDesc: item.errorMsg}));
}
}, res);
But since I am using Typescript
, I got error like this:
error TS2345: Argument of type '(prev: { approveList: any[]; rejectList: any[]; errorId: string; errorDesc: string; }, item: Resp...' is not assignable to parameter of type '(previousValue: { approveList: any[]; rejectList: any[]; errorId: string; errorDesc: string; }, c...'.
Type 'Promise<void>' is not assignable to type '{ approveList: any[]; rejectList: any[]; errorId: string; errorDesc: string; }'.
Property 'approveList' is missing in type 'Promise<void>'.
So I want to know two things:
- Why
forEach
await can not work? - Can I use promise function in reduce?