使用 Promise.allSettled() 执行一批承诺 [英] Execute batch of promise with Promise.allSettled()
问题描述
在 node v10.15.1 中,我尝试使用 Promise.allSettled()
来执行批量 Promise,但它抛出了一个错误
With node v10.15.1 I try to use Promise.allSettled()
to executes batches of Promise but it throw me an error
TypeError: Promise.allSettled 不是函数
TypeError: Promise.allSettled is not a function
Promise.all()
是否返回了一个承诺?
Is Promise.all()
returning a promise ?
下面的 Main
函数返回一个对象.其他函数使用一些 Promise 来创建它的子对象".
The Main
function below return an object.
Other functions use some Promises to create its "sub-object".
为什么我需要一批承诺":要创建子对象,必须解决所有必需的承诺.但并不是所有的子对象都需要在主对象"中.
Why I need "batch of promise" : To create a sub-object, all the required promises must be settled. But not all the sub-objects are needed in the "main object".
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();
预期对象的一个例子
{
foo: {
prop: 'example',
someOtherProps: 'We are there!'
},
baz: {
test: 50
}
}
推荐答案
Promise.allSettled在节点版本 >= 12.9
这篇关于使用 Promise.allSettled() 执行一批承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!