如何设置Promise等待的最大执行时间?

bob*_*nte 2 javascript

您将如何等待Promise解决/拒绝最多的执行时间?下面的代码显然是错误的,只是为了解释我要实现的目标。我一无所知。

await doSomething();
if ( executionTime > maxExecutionTime ) {
    doSomethingElse();
}
Run Code Online (Sandbox Code Playgroud)

这不是为了蓝鸟的承诺。

noa*_*hnu 13

您可以使用Promise.race()which 将在其可迭代中的第一个承诺解决或拒绝时立即解决/拒绝。例如

   
const longTask = () => new Promise(resolve =>
  setTimeout(() => resolve("Long task complete."), 300))

const timeout = (cb, interval) => () =>
  new Promise(resolve => setTimeout(() => cb(resolve), interval))

const onTimeout = timeout(resolve =>
  resolve("The 'maybeLongTask' ran too long!"), 200)

Promise.race([longTask, onTimeout].map(f => f())).then(console.log)
Run Code Online (Sandbox Code Playgroud)

唯一的问题是你不能真正取消“longTask”,因为它的执行时间很长。理论上,您要么设置一些标志(告诉它不要继续进入管道的下一阶段),要么在设计应用程序时考虑到承诺的后果。

看看当你交换200300间隔时会发生什么。

编辑:根据 spsaucier 的评论,我将每个承诺的执行推迟到 Promise.line 行。


Fal*_*aly 6

下面的代码将给您一些想法:

function doSomething(maxExecutionTime) {
    return new Promise(resolve => {
        setTimeout(() => resolve(true), 2000);  // this setTimeout simulates your async action which sould not exced maxExecutionTime
        setTimeout(() => resolve(false), maxExecutionTime);
    });
}

async function someFunc(maxExecutionTime) {
    var exced = await doSomething(maxExecutionTime);
    if (exced) {
        console.log("Doesn't exced max time");
    } else {
        console.log("Exced max time");
    }
}

someFunc(1000);
someFunc(3000);
Run Code Online (Sandbox Code Playgroud)