返回介绍

solution / 2800-2899 / 2821.Delay the Resolution of Each Promise / README_EN

发布于 2024-06-17 01:02:59 字数 2631 浏览 0 评论 0 收藏 0

2821. Delay the Resolution of Each Promise

中文文档

Description

Given an array functions and a number ms, return a new array of functions.

  • functions is an array of functions that return promises.
  • ms represents the delay duration in milliseconds. It determines the amount of time to wait before resolving each promise in the new array.

Each function in the new array should return a promise that resolves after a delay of ms milliseconds, preserving the order of the original functions array. The delayAll function should ensure that each promise from functions is executed with a delay, forming the new array of functions returning delayed promises.

 

Example 1:

Input: 
functions = [
   () => new Promise((resolve) => setTimeout(resolve, 30))
], 
ms = 50
Output: [80]
Explanation: The promise from the array would have resolved after 30 ms, but it was delayed by 50 ms, thus 30 ms + 50 ms = 80 ms.

Example 2:

Input: 
functions = [
    () => new Promise((resolve) => setTimeout(resolve, 50)),
    () => new Promise((resolve) => setTimeout(resolve, 80))
], 
ms = 70
Output: [120,150]
Explanation: The promises from the array would have resolved after 50 ms and 80 ms, but they were delayed by 70 ms, thus 50 ms + 70 ms = 120 ms and 80 ms + 70 ms = 150 ms.

 

Constraints:

  • functions is an array of functions that return promises
  • 10 <= ms <= 500
  • 1 <= functions.length <= 10

Solutions

Solution 1

function delayAll(functions: Function[], ms: number): Function[] {
  return functions.map(fn => {
    return async function () {
      await new Promise(resolve => setTimeout(resolve, ms));
      return fn();
    };
  });
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文