NodeJS Timeout a Promise if failed to complete in time

前端 未结 7 507
忘掉有多难
忘掉有多难 2020-11-27 04:07

How can I timeout a promise after certain amount of time? I know Q has a promise timeout, but I\'m using native NodeJS promises and they don\'t have .timeout function.

相关标签:
7条回答
  • 2020-11-27 04:39

    While the answers here are valid, you should not try to reinvent the wheel and just use one of the dozens available packages on NPM for the self-resolving promise.

    Here's one example from NPM:

    const { TimeoutResolvePromise, TimeoutRejectPromise } = require('nodejs-promise-timeout');
    const TIMEOUT_DELAY = 2000;
    
    // This promise will reject after 2 seconds:
    let promise1 = new TimeoutRejectPromise(TIMEOUT_DELAY, (resolve, reject) => {
      // Do something useful here, then call resolve() or reject()
    });
    
    0 讨论(0)
提交回复
热议问题