私はこのような約束の機能を使用しています:forEachのようなjavascriptの関数関数で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}));
}
}
これはうまく動作しますが、私は、いくつかの機能の機能を使用しようとする場合、私は私が
// 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});
を減らし、その後map
を使用する必要があることを見つけます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
機能を使用したい:
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>'.
だから私は二つのことを知りたい:
// 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
を使用しておりますのでを、私はこのようなエラーが発生しました
- なぜ
forEach
awaitできません仕事? - reduceでpromise関数を使用できますか?
の可能重複[使用非同期/ foreachループで待つ](http://stackoverflow.com/q/37576685/1048572) ( 'reduce'と同じです) – Bergi