返回介绍

solution / 2700-2799 / 2795.Parallel Execution of Promises for Individual Results Retrieval / README_EN

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

2795. Parallel Execution of Promises for Individual Results Retrieval

中文文档

Description

Given an array functions, return a promise promise. functions is an array of functions that return promises fnPromise. Each fnPromise can be resolved or rejected.  

If fnPromise is resolved:

    obj = { status: "fulfilled", value: _resolved value_}

If fnPromise is rejected:

    obj = { status: "rejected", reason: _reason of rejection (catched error message)_}

The promise should resolve with an array of these objects obj. Each obj in the array should correspond to the promises in the original array function, maintaining the same order.

Try to implement it without using the built-in method Promise.allSettled().

 

Example 1:

Input: functions = [
  () => new Promise(resolve => setTimeout(() => resolve(15), 100))
]
Output: {"t":100,"values":[{"status":"fulfilled","value":15}]}
Explanation: 
const time = performance.now()
const promise = promiseAllSettled(functions);
               
promise.then(res => {
  const out = {t: Math.floor(performance.now() - time), values: res}
  console.log(out) // {"t":100,"values":[{"status":"fulfilled","value":15}]}
})

The returned promise resolves within 100 milliseconds. Since promise from the array functions is fulfilled, the resolved value of the returned promise is set to [{"status":"fulfilled","value":15}].

Example 2:

Input: functions = [
  () => new Promise(resolve => setTimeout(() => resolve(20), 100)), 
  () => new Promise(resolve => setTimeout(() => resolve(15), 100))
]
Output: 
{
  "t":100,
  "values": [
      {"status":"fulfilled","value":20},
      {"status":"fulfilled","value":15}
  ]
}
Explanation: The returned promise resolves within 100 milliseconds, because the resolution time is determined by the promise that takes the longest time to fulfill. Since promises from the array functions are fulfilled, the resolved value of the returned promise is set to [{"status":"fulfilled","value":20},{"status":"fulfilled","value":15}].

Example 3:

Input: functions = [
    () => new Promise(resolve => setTimeout(() => resolve(30), 200)), 
    () => new Promise((resolve, reject) => setTimeout(() => reject("Error"), 100))
]
Output:
{
  "t":200,
  "values": [
    {"status":"fulfilled","value":30},
    {"status":"rejected","reason":"Error"}
  ]
}
Explanation: The returned promise resolves within 200 milliseconds, as its resolution time is determined by the promise that takes the longest time to fulfill. Since one promise from the array function is fulfilled and another is rejected, the resolved value of the returned promise is set to an array containing objects in the following order: [{"status":"fulfilled","value":30}, {"status":"rejected","reason":"Error"}]. Each object in the array corresponds to the promises in the original array function, maintaining the same order.

 

Constraints:

  • 1 <= functions.length <= 10

Solutions

Solution 1

type FulfilledObj = {
  status: 'fulfilled';
  value: string;
};
type RejectedObj = {
  status: 'rejected';
  reason: string;
};
type Obj = FulfilledObj | RejectedObj;

function promiseAllSettled(functions: Function[]): Promise<Obj[]> {
  return new Promise(resolve => {
    const res: Obj[] = [];
    let count = 0;
    for (let i in functions) {
      functions[i]()
        .then(value => ({ status: 'fulfilled', value }))
        .catch(reason => ({ status: 'rejected', reason }))
        .then(obj => {
          res[i] = obj;
          if (++count === functions.length) {
            resolve(res);
          }
        });
    }
  });
}

/**
 * const functions = [
 *  () => new Promise(resolve => setTimeout(() => resolve(15), 100))
 * ]
 * const time = performance.now()
 *
 * const promise = promiseAllSettled(functions);
 *
 * promise.then(res => {
 *   const out = {t: Math.floor(performance.now() - time), values: res}
 *   console.log(out) // {"t":100,"values":[{"status":"fulfilled","value":15}]}
 * })
 */
/**
 * @param {Array<Function>} functions
 * @return {Promise}
 */
var promiseAllSettled = function (functions) {
  return new Promise(resolve => {
    const res = [];
    let count = 0;
    for (let i in functions) {
      functions[i]()
        .then(value => ({ status: 'fulfilled', value }))
        .catch(reason => ({ status: 'rejected', reason }))
        .then(obj => {
          res[i] = obj;
          if (++count === functions.length) {
            resolve(res);
          }
        });
    }
  });
};

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

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

发布评论

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