如何停止处理继续通过承诺拒绝

How to stop processing continuing past a promise reject

我有异步代码,我想在 reject.

时停止 运行ning

注:

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 函数会按预期抛出超时错误。这会跳过“Record X successful ingestion...”消息并按预期跳转到 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)'
    }
}]

我希望拒绝会停止该承诺内的任何进一步处理(很像 return 会),我不会看到 'Rejected' 也不会 'Going to save file now...' console.logs...

我误会了什么?

添加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 子句,则需要添加一个变量来跟踪:

注意:这在这里没有帮助,因为 finally 应该执行而不管 catch 是否发生,但是如果你在 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;
}

调用拒绝没有什么特别之处。这只是一个功能。如果您想放弃进一步处理,您的函数应该 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;
}

表示第一个 reject(或 resolve)将定义一个 Promise 的 fullfilled 值,但它们主动不停止执行和 return 是必需的。