Promise.all在babel ES6实现中安装

Zla*_*tko 12 javascript node.js ecmascript-6 es6-promise babeljs

我正在使用babel我的node.js@0.10.x代码转换,我坚持承诺.

我需要allSettled-type功能,我可以使用q和/ bluebirdangular.$q例如.

在babel的核心-js上Promise,没有allSettled方法.

目前我正在使用q.allSettled解决方法:

import { allSettled } from 'q';

在babel polyfill中有类似的东西吗?或者,这对我来说是一个很好的算法来尝试实现?

Mic*_*pat 22

如果你看一下q.allSettled实现,你会发现它实际上非常简单.以下是使用ES6 Promises实现它的方法:

function allSettled(promises) {
    let wrappedPromises = promises.map(p => Promise.resolve(p)
        .then(
            val => ({ status: 'fulfilled', value: val }),
            err => ({ status: 'rejected', reason: err })));
    return Promise.all(wrappedPromises);
}
Run Code Online (Sandbox Code Playgroud)


Iva*_*son 9

2020 答案:

其他答案试图做的是实现Promise.allSettled自己。这已经由core-js项目完成了。

您需要做的是Promise.allSettled通过core-js为您制作 babel polyfill 。您配置它的方式是@babel/preset-env这样的:

presets: [
    ['@babel/preset-env', {
        useBuiltIns: 'usage',
        corejs: {version: 3, proposals: true},
    }],
],
Run Code Online (Sandbox Code Playgroud)

在您的构建工件中,这将添加一个调用,require("core-js/modules/esnext.promise.all-settled")将monkeypatches.allSettled函数添加到promises API。


Mar*_*aci 5

const allSettled = promises =>
  Promise.all(promises.map(promise => promise
    .then(value => ({ state: 'fulfilled', value }))
    .catch(reason => ({ state: 'rejected', reason }))
  ));
Run Code Online (Sandbox Code Playgroud)

或者如果你坚持要填充它:

if (Promise && !Promise.allSettled) {
  Promise.allSettled = function (promises) {
    return Promise.all(promises.map(function (promise) {
      return promise.then(function (value) {
        return { state: 'fulfilled', value: value };
      }).catch(function (reason) {
        return { state: 'rejected', reason: reason };
      });
    }));
  };
}
Run Code Online (Sandbox Code Playgroud)

取自这里


the*_*472 2

或者,哪种算法适合我尝试实现?

  1. 使用执行器函数创建一个新的 Promise
  2. 在执行器范围内使用计数器/结果数组
  3. 向每个父 Promise 注册一个 then() 回调,将结果保存在数组中
  4. 当计数器指示所有父级 Promise 均已完成时,解析/拒绝步骤 1 中的 Promise