【发布时间】:2018-09-03 02:12:38
【问题描述】:
我正在开发在 Node v6.11.5 上运行的 Firebase Cloud Function,因此我无法使用 Async Await(据我所知)。总体思路是,我遍历对象,提取数据,在不同的服务器上 ping 一个返回相关信息的 API,然后将新信息添加到对象,然后再将其添加到数组并继续。
API 返回信息,但不及时。如果我注销该对象,它会返回 3 个字段,但匹配项为空。
这会是我应该使用Promise.all() 的一个实例吗?如果是,如何使用。我尝试将getMatches 创建为一个promise,但该函数会继续运行。
...
const list = [];
...
return db.collection('users').get()
.then((snapshot) => {
return snapshot.forEach((doc) => {
const user = doc.data();
const obj = {};
obj.id = user.id;
obj.name = user.name;
obj.matches = [];
try {
getMatches(user.param1, user.param2)
.then(res => {
obj.matches.push(res);
})
}
catch (error) {
console.log('error => ', error);
}
list.push(obj);
});
})
.then(() => {
... sorts list ...
})
.then(() => {
... returns list to database ...
});
const getMatches = function (param1, param2) {
const url = 'https://something.herokuapp.com/callback.php';
return axios.post(url, qs.stringify({
data: param1,
name: param2
}))
.then(res => {
return res.data;
})
.catch(error => {
console.log('ERROR => ', error);
});
}
【问题讨论】:
-
如果您在 Firebase 项目中使用 TypeScript,则可以使用 async/await。它将转译为 ES6,Cloud Functions 将运行该 ES6。但这仍然无法帮助您处理 foreach 循环中的承诺。
标签: javascript firebase promise es6-promise