我正在创建一个 API 来与我的 Google Cloud Firestore 数据库交互。我正在我的应用程序中查询“管道”。该请求将返回一个管道数组(即 JSON 对象数组)。每个 JSON 对象都有一个用户属性,它等于字符串数组。每个字符串代表我数据库中的一个用户 ID。
我想做的是映射每个管道,然后在每个管道内映射用户数组,以异步调用我的数据库,以通过用户 ID 获取该用户的信息。
我在等待所有异步请求完成并正确返回数据时遇到了困难。目前我有以下代码:
pipelineResults.map(pipeline => {
pipeline.users = pipeline.users.map(user => {
return promises.push(db.collection('users')
.doc(user)
.get()
.then(snapshot => {
user = snapshot.data();
console.log(user);
return user;
}));
});
return pipeline;
});
Promise.all(promises)
.then(result => {
res.send(pipelineResults);
});
pipelineResults JSON 定义如下(映射之前):
[
{
"integrations": [
{
"dateAdded": {
"_seconds": 1553435585,
"_nanoseconds": 769000000
},
"vendorId": "abcdefg",
"integrationId": "ahdhfyer",
"addedBy": "xEcscnBo0PGgOEwb2LGj",
"used": 1
}
],
"users": [
"xEcscnBo0PGgOEwb2LGj"
],
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nec augue dapibus, interdum felis ac, tristique nunc. Donec justo ex, pulvinar a nisl et, consequat porta nunc.",
"scheduled": {
"isScheduled": false
},
"orgId": "ae35gt654",
"runInfo": null,
"name": "Development pipeline",
"teams": [
{
"users": [
"xEcscnBo0PGgOEwb2LGj"
],
"createdOn": {
"_seconds": 1553435585,
"_nanoseconds": 769000000
},
"id": "abfe4h6uuy",
"createdBy": "xEcscnBo0PGgOEwb2LGj",
"userCount": 1
}
],
"createdOn": {
"_seconds": 1553435585,
"_nanoseconds": 769000000
},
"createdBy": "xEcscnBo0PGgOEwb2LGj"
}
]
运行上述代码映射管道和用户后,管道上的用户属性现在只是一个内部为 1 的数组:
"users": [
1
]
用户对象应如下所示:
{ firstName: 'Alex',
activeIntegrations: 14,
position: 'Manager',
email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f7faf3eed6f7faf3eee1fffaf3efb8f5f9b8e3fd" rel="noreferrer noopener nofollow">[email protected]</a>',
lastName: 'Wiley',
}
我很确定我不会返回或等待异步调用。
摘要 在两个 map 函数内执行异步调用。
非常感谢任何帮助。
最佳答案
您正在尝试分配 pipeline.users,但 promise 尚未解决;试试这个:
试试这个:
return Promise.all(pipelineResults.map(pipeline => {
return Promise.all(pipeline.users.map(user =>
db.collection('users')
.doc(user)
.get()
.then(snapshot => {
user = snapshot.data();
console.log(user);
return user;
});
))
.then(users => {
pipeline.users = users;
});
}))
.then(() => res.send(pipelineResults));
关于javascript - 两个 Array.map 内的异步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55335944/