在调用返回承诺的函数时,除非删除异步运算符,否则返回 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()
才能启动,然后运行其余代码。
如果需要,我可以提供更多片段。
答案 0 :(得分:1)
您还需要返回此值:await Promise.all(allRelationshipQueries).then(allResults => {
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
正在返回,但所有这些都在箭头函数then(allResults => {
的范围内,因此您还需要像下面这样返回该函数:
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;