javascript - 异步承诺返回未定义或区域感知承诺
问题描述
调用返回承诺的函数时,除非删除异步运算符,否则返回未定义,然后返回 ZoneAwarePromise,但不包含任何数据。
我知道查询在函数执行时返回数据,但是它似乎没有将该数据传递给函数调用的实际返回部分。
我查看了几个没有回答这个问题的堆栈问题,包括这个问题: 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()
先触发,然后运行其余代码。
如果需要,我可以提供更多片段。
解决方案
您还需要返回这个:
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;
推荐阅读
- sql - 试图将行转换为列
- javascript - 使用 vuelidate 进行验证
- python - 如何在 Python 中隐藏控制台中的输入?
- c - 返回值 3221225477?
- c# - 初始化没有键的 DbSet 时出错:无法跟踪“MyEntity”类型的实例,因为它没有主键
- spring - Spring Boot 中的 @Transactional - 我相信先决条件已涵盖(公共、外部调用),但测试表明没有事务
- ruby-on-rails - “rails new”没有生成我项目的任何文件夹
- python - Seleium 和 Geckodriver 不工作 python
- python - 在尝试读取文件名以创建自定义数据集时读取矢量信息
- vba - 从列表框中删除项目(MS Access VBA)