如何在承诺中添加超时?

Mar*_*rio 1 javascript timeout node.js promise

我读过许多在承诺中添加超时的不同方法,但大多数(如果不是全部)似乎都利用了该setTimeout()方法。根据定义:

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
Run Code Online (Sandbox Code Playgroud)

我正在寻找的是一种表达方式:

"If the function executed inside the promise (that will either resolve or
reject the promise), does not complete within a specified x number of
milliseconds, automatically reject or raise an exception."
Run Code Online (Sandbox Code Playgroud)

如果这与上面定义的相同(使用该setTimeout()方法),我们将不胜感激!

eol*_*eol 10

您可以包装setTimeout在 Promise 中并创建一个小的“等待”函数,然后您可以将其与以下命令一起使用Promise.race

function wait(ms) {
   return new Promise((_, reject) => {
      setTimeout(() => reject(new Error('timeout succeeded')), ms);
   });
}

try {
  const result = await Promise.race([wait(1000), yourAsyncFunction()]);
} catch(err) {
  console.log(err);
} 
Run Code Online (Sandbox Code Playgroud)

使用此代码,如果解析/拒绝时间超过 1000 ,Promise.race则将拒绝,否则将从 中产生解析值。yourAsyncFunctionmsresultyourAsyncFunction