使用 Promise.allSettled() 执行一批承诺 [英] Execute batch of promise with Promise.allSettled()

查看:401
本文介绍了使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆