【发布时间】:2016-08-16 06:59:35
【问题描述】:
我正在使用这样的 promise 函数:
// 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}));
}
}
这个很好用,但是我想尝试使用一些功能函数,我发现我必须使用map然后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});
我发现forEach函数不能工作:
// 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}));
}
});
这不起作用,它只是返回初始值。 其实这让我很困惑,因为我await的功能,为什么不工作?
连我都想用reduce函数:
// 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);
但是由于我使用的是Typescript,所以我得到了这样的错误:
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>'.
所以我想知道两件事:
- 为什么
forEachawait 不起作用? - 可以在reduce中使用promise函数吗?
【问题讨论】:
-
Using async/await with a forEach loop 的可能重复项(
reduce相同)
标签: javascript typescript functional-programming promise async-await