亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

解決數組或承諾并獲得結果

解決數組或承諾并獲得結果

30秒到達戰場 2023-04-20 17:07:43
我正在嘗試映射和格式化數據以將其呈現到表格中。我嘗試使用 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  });}我的數據復制變量只返回為:[[PromiseState]]: "fulfilled"[[PromiseResult]]: Array(10)結果是“setTenants”函數的正確結果。
查看完整描述

1 回答

?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

我有一系列的承諾,我正試圖用Promise.all().


Promise.all不解決承諾(或者我認為你的意思是在這種情況下解決1)。它允許您觀察promises 被結算的結果。這不會讓他們安定下來。


您的setTenants函數返回一個承諾。要使用其實現值,您必須使用.then或await(在async函數中)。請記住,截至 whensetTenants返回其承諾,已啟動的操作可能尚未完成。


所以


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);

1 一些承諾術語:

  • fulfill - 將 promise 狀態從pending更改為fulfilled并具有特定的fulfillment 值

  • reject - 將 promise 狀態從pending更改為rejected并給出特定的拒絕原因

  • 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);

});


查看完整回答
反對 回復 2023-04-20
  • 1 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號