30秒学会 JavaScript 片段 · 2023年12月1日

30秒学会 JavaScript 片段 – Resolve promise after given amount of time

Creates a promise that resolves after a given amount of time to the provided value.

  • Use the Promise constructor to create a new promise.
  • Use setTimeout() to call the promise’s resolve function with the passed value after the specified delay.

代码实现

const resolveAfter = (value, delay) =>
  new Promise(resolve => {
    setTimeout(() => resolve(value, delay));
  });

resolveAfter('Hello', 1000);
// Returns a promise that resolves to 'Hello' after 1s

翻译自:https://www.30secondsofcode.org/js/s/resolve-promise-after-amount-of-time