簡體   English   中英

異步 Promise 返回未定義或區域感知 promise

[英]Async Promise returns undefined or zone aware promise

當調用返回 promise 的 function 時,除非刪除異步運算符,否則返回未定義,然后返回 ZoneAwarePromise,但不包含數據。

我知道查詢在 function 執行時返回數據,但是它似乎沒有將該數據傳遞給 function 調用的實際返回部分。

我查看了幾個沒有回答這個問題的堆棧問題,包括這個問題: Async/Await with Request-Promise returns Undefined

這是使用 REST 端點來提取數據,console.logs 確實顯示數據是正確的,但是返回未定義

     this.allPeople.forEach(async person => {
          const dodString = await this.getRelatedRecords(person); //undefined
    }

這是返回 promise / 數據的主要 function

async getRelatedRecords(person) {
    // function truncated for clarity
    // ...
    //
    console.warn('This async should fire first');
    selPeopleTable.relationships.forEach(relationship => {
    allRelationshipQueries.push(
      arcgisService.getRelatedTableData(
        selPeopleTable.url, [person[oidField.name]], relationship.id, relationship.name),
      );
    });
    await Promise.all(allRelationshipQueries).then(allResults => {
      console.log('Inside the Promise');
      // The Specific node I am looking for
      const data = allResults[1].results.relatedRecordGroups[0].relatedRecords[0].attributes.dod;
    console.log(data); // Shows correctly as the data I am looking for  
    return data;
    }).catch(function(data){
      console.log('there might be data missing', data);
    });
  }

刪除 ASYNC 運算符會導致getRelatedRecords()在包含 function 之后觸發和/或返回不包含數據的“ZoneAwarePromise”。 我需要先觸發getRelatedRecords() ,然后運行代碼的 rest。

如果需要,我可以提供更多片段。

區域感知 Promise 區域感知承諾

當異步操作符(我認為)正確設置時在此處輸入圖像描述

您還需要返回這個:

await Promise.all(allRelationshipQueries).then(allResults => {
    console.log('Inside the Promise');
    // The Specific node I am looking for
    const data = allResults[1].results.relatedRecordGroups[0].relatedRecords[0].attributes.dod;
    console.log(data); // Shows correctly as the data I am looking for  
    return data;
})

上述塊中的return正在返回,但所有這些都在箭頭 function 的 scope 中,即then(allResults => {所以你還需要像這樣返回這個 ZC1C425268E68385D1AB5074C17A94F:

return await Promise.all(allRelationshipQueries).then(allResults => {

方法#2:第二種方法是將其存儲到變量中,如下所示:

let dataToReturn = await Promise.all(allRelationshipQueries).then(allResults => {
    console.log('Inside the Promise');
      // The Specific node I am looking for
    const data = allResults[1].results.relatedRecordGroups[0].relatedRecords[0].attributes.dod;
    console.log(data); // Shows correctly as the data I am looking for  
    return data;
    }).catch(function(data){
      console.log('there might be data missing', data);
    });
return dataToReturn;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM