异步承诺 returns 未定义或区域感知承诺

Async Promise returns undefined or zone aware promise

当调用 returns 承诺的函数时,返回为 undefined 除非异步运算符被删除,然后 returns ZoneAwarePromise,但不包含数据。

我知道函数执行时查询 return 的数据,但是它似乎没有将该数据传递给函数调用的实际 return 部分。

我看了几个没有回答这个问题的堆栈问题,包括这个问题:

这是使用 REST 端点提取数据,console.logs 显示数据正确,但是 return 返回未定义

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

这是return承诺/数据

的主要功能
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() 在包含函数和/或 return 不包含数据的 'ZoneAwarePromise' 之后触发。我需要 getRelatedRecords() 先触发,然后 运行 剩下的代码。

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

区域感知承诺

当异步运算符(我认为)设置正确时

你也需要return这个:

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 是 returning 但所有这些都在箭头函数的范围内,即 then(allResults => { 所以你还需要 return这个函数是这样的:

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;