Zla*_*tko 12 javascript node.js ecmascript-6 es6-promise babeljs
我正在使用babel我的node.js@0.10.x代码转换,我坚持承诺.
我需要allSettled-type功能,我可以使用q和/ bluebird或angular.$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)
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。
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)
取自这里
| 归档时间: |
|
| 查看次数: |
3602 次 |
| 最近记录: |