Async Await Promise.all Array.map的行为不符合预期。不确定为什么
我在其中一个项目中的async函数中有以下内容。 matchCamera
,matchIP
和matchAudio
都返回布尔值或错误。
如果一个错误被返回我会期望它落入我的主捕获,所以我可以处理它,但这不会发生。
try {
// .... Additional code here
const typecheck = await Promise.all(
evoCfg.cameras.map(async camera => {
if (camera.type === 'H264') {
return await matchCamera(camera);
} else if (camera.type === 'RTSP') {
return await matchIP(camera);
} else if (camera.type === 'AUDIO') {
return await matchAudio(camera);
} else {
// Motion JPEG
return true;
}
})
);
// .... additional code here
console.log('results:);
console.dir(typecheck, {depth: null, colors: true});
} catch (e) {
console.error('In Master Catch:', e);
}
我在导致错误情况时不断获得的输出是:
results:
[ true,
true,
true,
true,
true,
true,
Error: MAC for IP Cam not found on Network: 00:11:22:33:44:55
at matchIP (/file.js:58:15)
at process._tickCallback (internal/process/next_tick.js:68:7),
true ]
我期待:
In Master Catch: MAC for IP Cam not found on Network: 00:11:22:33:44:55
at matchIP (/file.js:58:15)
at process._tickCallback (internal/process/next_tick.js:68:7)
const matchIP = async source => {
let arpScan = [];
for (const c in obj.arr){
if(obj.arr[c].name === source.source) {
try {
arpScan = await scannerP();
let arpIdx = searchObjArray(source.mac, source.mac, 'mac', 'mac', arpScan);
if(arpIdx === -1) {
// not found on network
throw new Error(`MAC for IP Cam not found on Network: ${source.mac}`);
}
for (const cs in obj.arr[c].sources) {
if (
obj.arr[c].sources[cs].id === arpScan[arpIdx].mac &&
obj.arr[c].sources[cs].url === `rtsp://${arpScan[arpIdx].ip}/${source.streamPort}`
) {
return true;
}
}
let recorderIdx = searchObjArray(
'rtsp',
source.mac,
'fmt',
'id',
obj.arr[c].sources
);
source.streamAddress = arpScan[arpIdx].ip;
obj.arr[c].sources[recorderIdx].url = `rtsp://${arpScan[arpIdx].ip}/${source.streamPort}`;
return false;
} catch (e) {
return e;
}
}
}
};
回答如下:
问题是你的matchIP
功能有
try {
// ... code
catch (e) {
return e;
}
所以它将错误作为一个值返回,而不是将它抛给你的外部块来捕获。
此外,正如其他人所指出的那样。你通常在你的Promise.all
函数中使用await
来击败map
的价值。拿出await
s。