【问题标题】:How to set maximum execution time for a Promise await?如何设置 Promise 等待的最大执行时间?
【发布时间】:2017-12-08 16:53:54
【问题描述】:

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

await doSomething();
if ( executionTime > maxExecutionTime ) {
    doSomethingElse();
}

这不是蓝鸟的承诺。

【问题讨论】:

  • 你有什么样的承诺?如果是 bluebird Promise,您可以这样做:await doSomething().timeout(100);。如果它不是 bluebird Promise 而你想使用 bluebird,你可以这样做:await Promise.resolve( doSomething() ).timeout(100);,其中 Promise 是 bluebird Promise 构造函数。

标签: javascript


【解决方案1】:

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

   
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)

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

看看当你交换 200 和 300 间隔时会发生什么。

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

【讨论】:

  • 这样写,onTimeout 是在声明时调用函数,而在比赛期间不执行。
  • 好点,我已经更新了 sn-p 以将执行至少延迟到比赛线
  • 作者要求一种方法来限制调用函数的最大执行时间,而您的答案是如何从接收函数中做到这一点。仅当您是代码的所有者时,此方法才有效。如果我正在等待来自外部 API 的响应怎么办?
  • @Nadav 这是同一个概念。我只是提供了一个示例承诺。您可以将 longTask 替换为外部 API,假设外部 API 是一个承诺。
【解决方案2】:

下面的代码会给你一些想法:

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);

【讨论】:

    【解决方案3】:

    在 ECMA6 中你可以这样做:

    let promise = new Promise((resolve, reject) => {
      let wait = setTimeout(() => {
        clearTimeout(wait);
        resolve('Timed out after 200 ms..');
      }, 200)
    })
    

    【讨论】:

    • clearTimeout 有什么作用?你能显示更多细节吗?它如何帮助设置特定功能的时间限制或执行时间?
    【解决方案4】:

    按照 noahnu 的建议,您可以使用 Promise.race。您可以将其包装在一个接受承诺的函数中。

    使用一些语法糖,您可以使用thisOrThat,它采用logic,一个采用两个函数的函数,first 和second。您可以在此处应用逻辑来尝试第一个函数以及何时尝试第二个函数(在我们的例子中,如果第一个函数在特定时间内没有解决,则尝试第二个函数)。

    thisOrThat 然后接受一个参数first,它是一个返回承诺的函数(在我们的例子中为doSomething。

    thisOrThat 返回一个具有or 属性的对象,该属性接受一个返回承诺的函数。该参数称为second,并作为second(在我们的例子中为doSomethingElse)传递给logic。

    var timeoutPromise =
      time    =>
      promiseFn =>
        Promise.race([
          promiseFn(),
          new Promise(
            (_,r)=>
              setTimeout(
                _=>r("timed out")
                ,time
              )
            )
        ]);
    
    var thisOrThat =
      logic     =>
      first  => ({
        or:second=>
          logic(first)(second)
      });
    var within75ms = thisOrThat
      (first=>second=>
        timeoutPromise(75)(first)
        .catch(_=>second())
      );
    var within25ms = thisOrThat
      (first=>second=>
        timeoutPromise(25)(first)
        .catch(_=>second())
      );
    
    var doSomething = () =>
      console.log("do something called")||
      new Promise(r=>setTimeout(x=>r("something"),50));
    var doSomethingElse = () =>
      console.log("do something else called") ||
      new Promise(r=>setTimeout(x=>r("something else"),50));
    
    
    async function someFunc() {
      const doesNotTimeOut = 
        await within75ms(doSomething).or(doSomethingElse);
      console.log("within 75ms resolved to:",doesNotTimeOut);
    
      const doesTimeOut = 
        await within25ms(doSomething).or(doSomethingElse)
      console.log("within 25ms resolved to:",doesTimeOut);
    };
    someFunc();

    【讨论】:

    • 这是我见过的最奇怪的 JS 格式。
    【解决方案5】:

    我用过 Promise.race

    // Try to get config from mongo
    async function getProjectConfigThreshold(projectName) {
        function onTimeoutResolveDefaultThreshold() {
            return new Promise(async (resolve) => {
                setTimeout(() => {
                    resolve(DEFAULT_THRESHOLD);
                }, 2000)
            });
        }
    
        async function getThresholdFromProjectConfig() {
            const projectConfig = await getProjectsConfig(projectName);
            const threshold = projectConfig.threshold || DEFAULT_THRESHOLD;
            return threshold;
        }
    
        return await Promise.race([getThresholdFromProjectConfig(), onTimeoutResolveDefaultThreshold()]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多