最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Async Await Promise.all Array.map的行为不符合预期。不确定为什么

运维笔记admin19浏览0评论

Async Await Promise.all Array.map的行为不符合预期。不确定为什么

Async Await Promise.all Array.map的行为不符合预期。不确定为什么

我在其中一个项目中的async函数中有以下内容。 matchCameramatchIPmatchAudio都返回布尔值或错误。

如果一个错误被返回我会期望它落入我的主捕获,所以我可以处理它,但这不会发生。

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的价值。拿出awaits。

发布评论

评论列表(0)

  1. 暂无评论