解决数组或承诺并获得结果

Resolving an array or promises and getting the result

我正在尝试映射和格式化数据以将其呈现为 table。我有一系列承诺,我试图用 Promise.all() 来解决。但它似乎没有返回承诺的结果。

我的代码如下:

const formatData = (data) => {
  let dataCopy = data;

  if (dataCopy.items && _.has(dataCopy.items[0], 'tenantId')) {
      dataCopy.items = setTenants(dataCopy)
  }

  // format parameters or table render
  // other formatting for the table
  return dataCopy.items.map(item => ({
      ...item,
      created: new Date(item.created).toDateString(),
      updated: new Date(item.updated).toDateString(),
      ...(item.active && { active: item.active.toString() })
  }));
};

const setTenants = (data) => {
  const promises = data.items.map(item => {
      return getTenant(item)
  })
  return Promise.all(promises).then(res => { return res })
}

const getTenant = (row) => {
  return tenantService.getTenantById(row.tenantId).then(res => {
      // set name as the tenant param for the table
      row.tenant = res.name
      return row
  });
}

我的数据只复制变量 returns as :

[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(10)

其中结果是 'setTenants' 函数的正确结果。

I have an array of promises that I'm attempting to resolve with Promise.all().

Promise.all 没有解决承诺(或者我认为你的意思是在这种情况下解决¹)。它允许您观察 承诺的结果。它不会他们安定下来。

你的setTenants函数returns一个承诺。要使用其实现值,您必须使用 .thenawait(在 async 函数中)。请记住,截至 setTenants returns 它的承诺,已经开始的操作 可能尚未完成 .

所以

setTenants(/*...*/)
.then(results => {
    // use results...
})
.catch(error => {
    // handle/report error
});

或者,在 async 函数中:

const results = await setTenants(/*...*/);

(也许使用 try/catch 来处理拒绝,尽管通常您只想让它传播到调用者并在那里处理它。)


旁注:此代码中的 then 回调毫无意义:

return Promise.all(promises).then(res => { return res })

应该是:

return Promise.all(promises);

¹ 一些承诺术语:

  • fulfill - 将承诺状态从 pending 更改为 fulfilled 具有特定 履行价值
  • reject - 将 promise 状态从 pending 更改为 rejected =53=]拒绝原因
  • resolve - 直接(通过履行或拒绝)或间接(通过使其结果取决于另一个承诺的结果)来确定承诺的最终结果

重要的是要认识到,如果已解决的承诺 解决为 另一个承诺并且另一个承诺处于待定状态,则该承诺仍将处于待定状态。

这是一个例子:

const p1 = new Promise(resolve => {
    setTimeout(resolve, 800, 42);
});

// This could also be written: `const p2 = Promise.resolve(p1);`
const p2 = new Promise(resolve => {
    resolve(p1);
});

// At this point, both `p1` and `p2` are *pending*; `p2` is *resolved to*
// `p1`, but neither `p1` nor `p2` is *settled* yet

p2
.then(value => {
    // At this point, `p2` is *fulfilled* (one of the two kinds of *settled*)
    console.log(value);
})
.catch(error => {
    // At this point, `p2` is *rejected* (one of the two kinds of *settled*)
    console.error(error);
});