我有异步代码,我想在reject
时停止运行。
注:
let ingestPromises = event.Records.map(async (record, i) => {
let camera = JSON.parse(record.body)
return new Promise(async (resolve, reject) => {
let imageBuffer;
try {
imageBuffer = await retrieveImageFromURI(camera.ing_uri)
console.log(`Record #${i} Successful Ingestion from URI`);
} catch (err) {
console.log("Going to reject");
reject({ 'Task': `Attempting to pull image from camera (${camera.camName}`})
console.log("Rejected");
}
console.log("Going to save file now...");
// ... blah blah more code ...
})}
let settledPromises = await Promise.allSettled(ingestPromises)
console.log('All promises settled :>> ', settledPromises);
当我针对无效的uri运行此操作时,retrieveImageFromURI
函数会按预期抛出超时错误。这跳过了";记录X次成功摄取"消息,并按预期跳转到catch块。然而,事情发展得出乎意料。
当retrieveImageFromURI
抛出错误时,上面代码的输出如下:
Going to reject Rejected Going to save file now... All promises settled :>> [ { status: 'rejected', reason: { Task: 'Attempting to pull image from camera (TEST Camera)' } }]
我希望拒绝会停止该承诺内的任何进一步处理(就像返回一样(,我不会看到"被拒绝"或"现在要保存文件…"console.log…
我误解了什么?
调用reject没有什么特别之处。这只是一个函数。如果你想保释进一步的处理,你的函数应该是return
。
try {
imageBuffer = await retrieveImageFromURI(camera.ing_uri)
console.log(`Record #${i} Successful Ingestion from URI`);
} catch (err) {
console.log("Going to reject");
reject({ 'Task': `Attempting to pull image from camera (${camera.camName}`})
console.log("Rejected");
return;
}
添加return
以停止执行,由于reject
只是一个函数,它不能使函数停止执行。
try {
// ...
} catch (err) {
console.log("Going to reject");
reject({
'Task': `Attempting to pull image from camera (${camera.camName}`
});
console.log("Rejected");
return;
}
如果您有finally
子句,则需要添加一个变量来跟踪:
注意:这在这里没有帮助,因为无论是否发生catch
,finally
都应该执行,但如果在catch
内部有额外的检查,return
将进入finally
,因此需要一个额外的变量。
let shouldReturn = false;
try {
// ...
} catch (err) {
console.log("Going to reject");
reject({
'Task': `Attempting to pull image from camera (${camera.camName}`
});
console.log("Rejected");
let shouldReturn = true;
return;
} finally {
if (shouldReturn) return;
}
早期解决/拒绝后是否需要返回?表示第一个reject
(或resolve
(将定义Promise的已满值,但它们主动不停止执行,需要返回。