【问题标题】:How to aggregate 2d array Promises?如何聚合二维数组 Promise?
【发布时间】:2021-06-17 20:37:35
【问题描述】:

我正在尝试解析一个 2d 维度的 promise 数组,但我无法解析它,并且在我使用 Promise.All 后它显示为待处理状态。
谁能建议我如何解决这个问题?

这是我用来获取用户信息的getAuth 函数:

const getAuth = async(phoneNumber) => {
   return db.getUserByPhoneNumber(phoneNumber).catch((error) => {
        // console.log(error)
        return {
          phoneNumber,
          uid: null,
          email: "",
          displayName: "",
          emailVerified: false,
          disabled: false,
        };
   });
};

并使用它我正在尝试解决phoneNumbers 的数组,但在解决数组后它仍然显示待处理状态:

const x = async() => {
   const xy = [
        ["+9188", "+9199"],
        ["+9188", "+9199", "+9188"],
   ];
   const p = [];
   xy.forEach((doc) => {
      p.push(doc.map(getAuth));
   });
   console.log(p, "P");
   const [users] = await Promise.all([Promise.all(p)]);
   console.log(users, "users");
};
x();

这是我得到的输出:

    [ [ Promise { <pending> }, Promise { <pending> } ],
      [ Promise { <pending> },
        Promise { <pending> },
        Promise { <pending> } ] ] 'P'
    [ [ Promise { <pending> }, Promise { <pending> } ],
      [ Promise { <pending> },
        Promise { <pending> },
        Promise { <pending> } ] ] 'users'

【问题讨论】:

    标签: javascript arrays promise es6-promise


    【解决方案1】:

    使用嵌套的Array.map()Promise.all()组合等待数组的每一级解析:

    const getAuth = phoneNumber => Promise.resolve(`resolved-${phoneNumber}`);
    
    const x = phoneNumbers =>
      // map and wait for each sub-array to resolve
      Promise.all(phoneNumbers.map(nums =>
        // map and wait for each getAuth to resolve
        Promise.all(nums.map(getAuth)) 
      ))
      
    const phoneNumbers = [
      ["+9188", "+9199"],
      ["+9188", "+9199", "+9188"],
    ];
    
    x(phoneNumbers)
      .then(console.log)

    【讨论】:

      猜你喜欢
      • 2016-08-24
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多