关于firebase函数,我有下一个代码:
app.post('/licence', (req, res) => {
let { email, machine_id, product_id } = req.body
let arr_product_ids = product_id.split(",").map(function (val) { return {product_id: val}; });
let res_to_print = '';
return new Promise((resolve, reject) => {
arr_product_ids.forEach(function(n){
res_to_print = asyncGetLicences(n.product_id, email, machine_id)
console.log('res_to_print')
console.log(res_to_print)
});
}).then((state) => {
console.log(state)
})
.catch((error) => {
console.log(error)
});
我需要调用查询两次才能调用firebase查询!所以我称之为foreach循环。
以下是需要调用两次的函数:
function asyncGetLicences(product_id, email, machine_id) {
licences_to_print = []
db.collection('licences', 'desc').where('email', '==', email).where('product_id', '==', product_id).get()
.then(data => {
let licences = []
data.forEach(doc => {
console.log(doc.data().email);
licences.push({
id: doc.id,
email: doc.data().email,
product: doc.data().product,
createdAt: doc.data().createdAt
});
});
if(typeof this.licences !== 'undefined' && this.licences.length > 0){
let string = email+machine_id+product_id+'55';
let api = md5(string);
let uppercase = api.toUpperCase()+'-';
licences_to_print.push(uppercase);
return licences_to_print
//return res.send('"'+uppercase+'"');//res.json(this.licences);
} else {
return licences_to_print
//return res.status(200).send('nothing to find');
}
})
}
我正在为这个简单的承诺而挣扎。。。我在PHP中有这个,它很容易,但node.js和firebase让我卡住了!
将数组中的所有promise添加到Promise.all()
中,然后在主函数中返回。这将集体异步地从每个承诺中获得回报,并返回单个集体响应。
app.post('/licence', (req, res) => {
let { email, machine_id, product_id } = req.body
let arr_product_ids = product_id.split(",").map(function (val) { return {product_id: val}; });
let res_to_print = '';
const promises = [] // Empty array
arr_product_ids.forEach(function(n){
promises.push(asyncGetLicences(n.product_id, email, machine_id));
});
return Promise.all(promises).then(res_to_print => {
console.log('res_to_print')
console.log(res_to_print)
}).catch((error) => {
console.log(error)
});
第二个功能:
function asyncGetLicences(product_id, email, machine_id) {
licences_to_print = []
return new Promise((resolve, reject) => {
db.collection('licences', 'desc').where('email', '==', email).where('product_id', '==', product_id).get()
.then(data => {
let licences = []
data.forEach(doc => {
console.log(doc.data().email);
licences.push({
id: doc.id,
email: doc.data().email,
product: doc.data().product,
createdAt: doc.data().createdAt
});
});
if(typeof this.licences !== 'undefined' && this.licences.length > 0){
let string = email+machine_id+product_id+'55';
let api = md5(string);
let uppercase = api.toUpperCase()+'-';
licences_to_print.push(uppercase);
resolve(licences_to_print)
//return res.send('"'+uppercase+'"');//res.json(this.licences);
} else {
resolve(licences_to_print)
//return res.status(200).send('nothing to find');
}
}))