【发布时间】:2020-02-19 01:24:25
【问题描述】:
当调用返回 promise 的函数时,返回为 undefined 除非异步运算符被删除,然后返回 ZoneAwarePromise,但不包含数据。
我知道当函数执行时查询返回数据,但它似乎没有将该数据传递给函数调用的实际返回部分。
我查看了几个未回答此问题的 Stack 问题,包括以下问题: Async/Await with Request-Promise returns Undefined
这是使用 REST 端点来提取数据,console.logs 确实显示数据是正确的,但是返回未定义
this.allPeople.forEach(async person => {
const dodString = await this.getRelatedRecords(person); //undefined
}
这是返回承诺/数据的主函数
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() 在包含函数之后触发和/或返回不包含数据的“ZoneAwarePromise”。我需要 getRelatedRecords() 先触发,然后运行其余代码。
如果需要,我可以提供更多的 sn-ps。
【问题讨论】:
-
当你想使用
async/await时不要使用then!你只是来自 promise 回调的returning,而不是来自函数。
标签: javascript typescript promise angular-promise angular8