使用 node v10.15.1 我尝试使用Promise.allSettled()Promise 执行批处理,但它给我一个错误
类型错误:Promise.allSettled 不是函数
是Promise.all()返回承诺吗?
Main下面的函数返回一个对象。其他函数使用一些 Promise 来创建它的“子对象”。
为什么我需要“批量承诺”:要创建子对象,必须解决所有必需的承诺。但并非所有子对象都需要在“主对象”中。
const path = require('path');
const os = require('os');
const si = require('systeminformation');
function getFoo() {
// all these promises have to be settled to construct the sub-object
return Promise.all([si.system(), si.chassis()]).then(([system, chassis]) => {
return { /* hidden for brevity : use system and chassis to return a single object */ };
})
.catch(ex => { /* hidden for brevity */ });
}
function getBar() {
// all these promises have to be settled to construct the sub-object
return Promise.all([si.osInfo(), si.uuid()]).then(([osInfo, uuid]) => {
return { /* hidden for brevity : use osInfo and uuid to return a single object */ };
})
.catch(ex => { /* hidden for brevity */ });
}
function getBaz() {
// all these promises have to be settled to construct the sub-object
return Promise.all([os.networkInterfaces(), si.networkInterfaceDefault()]).then(([interfaces, defaultInterface]) => {
return { /* hidden for brevity : use interfaces and defaultInterface to return a single object */ };
})
.catch(ex => { /* hidden for brevity */ });
}
function Main() {
// some of these promises can be rejected
Promise.allSettled([ getFoo(), getBar(), getBaz() ])
.then(([foo, bar, baz]) => {
return { foo, bar, baz }
})
.catch(ex => { /* hidden for brevity */ });
}
Main();
Run Code Online (Sandbox Code Playgroud)
{
foo: {
prop: 'example',
someOtherProps: 'We are there!'
},
baz: {
test: 50
}
}
Run Code Online (Sandbox Code Playgroud)
Promise.allSettled 尚不可用于 Node 环境。
更新:此功能从节点 12.9.0 开始可用。
对于旧版本,您可以使用 npm 包作为解决方法:es-shims/Promise.allSettled。