gpt4 book ai didi

javascript - 谷歌云函数http触发foreach循环的问题

转载 作者:行者123 更新时间:2023-12-02 23:43:26 24 4
gpt4 key购买 nike

我在云函数中有一个 http 触发器似乎正在工作,但是我收到的一些日志让我对 foreach 循环产生了疑问。

问题:是否有更好的方法来编写此函数而不必使用 foreach 循环?

功能:

const gamePin = req.body.gamepin
const numPlayers = req.body.playercount.toString()

var getGame = admin.firestore().collection('games')
getGame = getGame.where('gid', '==', gamePin).get()
.then(snapshot => {
if (!snapshot.empty) {

console.log(`BODY: ${JSON.stringify(req.body)}`);

snapshot.forEach(doc => {
let data = doc.data()
data.id = doc.id

console.log(`DOC DATA: ${JSON.stringify(data)}`);

const currentNumPlayers = data.playercount
console.log(`currentNumPlayers: ${JSON.stringify(currentNumPlayers)}`);

const newPlayerCount = +numPlayers + +currentNumPlayers
console.log(`newPlayerCount: ${JSON.stringify(newPlayerCount)}`);

const newPlayerCountToString = newPlayerCount.toString()
console.log(`newPlayerCountToString: ${JSON.stringify(newPlayerCountToString)}`);

var updateGame = admin.firestore().collection('games').doc(data.id)
updateGame.update({
playercount: newPlayerCountToString
}).then(res => {
console.log(`COMPLETED UPDATE: ${JSON.stringify(res)}`);
res.send({ status: 200, message: 'Game: updated.', pin: gamePin })
}).catch(err => {
console.log(`ERROR IN QUERY: ${JSON.stringify(err)}`);
res.status(500).send(err)
})

})

} else {
console.log('could not find a match ', snapshot)
res.send({ status: 400, message: 'Error. could not find a match' })
}
})
.catch(error => {
console.log(error)
res.status(500).send(error)
})

以下是与所有这些 console.logs 一起使用的相应日志

enter image description here

更新:

exports.addPlayerToGame = functions.https.onRequest((req, res) => {
return cors(req, res, () => {


// Check for POST request
if (req.method !== "POST") {
res.status(400).send('Please send a POST request');
return;
}
const gamePin = req.body.gamepin
const numPlayers = req.body.playercount.toString()

var getGame = admin.firestore().collection('games')
getGame = getGame.where('gid', '==', gamePin).get()
.then(snapshot => {
if (!snapshot.empty) {

console.log(`BODY: ${JSON.stringify(req.body)}`);
const doc = snapshot.docs[0];
let data = doc.data()
data.id = doc.id

const currentNumPlayers = data.playercount
console.log(`currentNumPlayers: ${JSON.stringify(currentNumPlayers)}`);

const newPlayerCount = +numPlayers + +currentNumPlayers
console.log(`newPlayerCount: ${JSON.stringify(newPlayerCount)}`);

const newPlayerCountToString = newPlayerCount.toString()
console.log(`newPlayerCountToString: ${JSON.stringify(newPlayerCountToString)}`);

return admin.firestore().collection('games').doc(data.id)
.update({
playercount: newPlayerCountToString
})
.then((res) => {
console.log(`COMPLETED UPDATE: ${JSON.stringify(res)}`);
res.send({
status: 200,
message: 'Game: updated.',
pin: gamePin
});
})
.catch(err => {
console.log(`ERROR IN QUERY: ${JSON.stringify(err)}`);
// throw new Error(err);
res.status(500).send(err)
});

} else {
console.log('could not find a match ', snapshot)
res.send({ status: 400, message: 'Error. could not find a match' })
}

console.log(`END:`);
})
.catch(error => {
console.log(error)
res.status(500).send(error)
})

})

})

最佳答案

由于您想要并行执行多个异步任务(调用 update() 方法,该方法返回 Promise),因此需要使用 Promise.all() ,如下:

var getGame = admin.firestore().collection('games');
getGame = getGame
.where('gid', '==', gamePin)
.get()
.then(snapshot => {
if (!snapshot.empty) {
console.log(`BODY: ${JSON.stringify(req.body)}`);

const promises = [];

snapshot.forEach(doc => {
let data = doc.data();
data.id = doc.id;

console.log(`DOC DATA: ${JSON.stringify(data)}`);

const currentNumPlayers = data.playercount;
console.log(`currentNumPlayers: ${JSON.stringify(currentNumPlayers)}`);

const newPlayerCount = +numPlayers + +currentNumPlayers;
console.log(`newPlayerCount: ${JSON.stringify(newPlayerCount)}`);

const newPlayerCountToString = newPlayerCount.toString();
console.log(
`newPlayerCountToString: ${JSON.stringify(newPlayerCountToString)}`
);

var updateGame = admin
.firestore()
.collection('games')
.doc(data.id);

promises.push(
updateGame.update({
playercount: newPlayerCountToString
})
);
});

return Promise.all(promises)
.then(results => {
console.log(`COMPLETED UPDATE: ${JSON.stringify(res)}`);
res.send({
status: 200,
message: 'Game: updated.',
pin: gamePin
});
})
.catch(err => {
console.log(`ERROR IN QUERY: ${JSON.stringify(err)}`);
throw new Error(err);
});
} else {
console.log('could not find a match ', snapshot);
throw new Error('Error. could not find a match');
}
})
.catch(error => {
console.log(error);
res.status(500).send(error);
});
<小时/>

根据您的评论进行更新:如果您确定 Query 仅返回一份文档(“只有一个文档包含该游戏 pin”)您可以使用 docs QuerySnapshot 的属性,返回“QuerySnapshot 中所有文档的数组”,并执行以下操作:

var getGame = admin.firestore().collection('games');
getGame = getGame
.where('gid', '==', gamePin)
.get()
.then(snapshot => {
if (!snapshot.empty) {
console.log(`BODY: ${JSON.stringify(req.body)}`);

const doc = snapshot.docs[0];

let data = doc.data();
data.id = doc.id;

const currentNumPlayers = data.playercount;
const newPlayerCount = +numPlayers + +currentNumPlayers;
const newPlayerCountToString = newPlayerCount.toString();


return admin.firestore().collection('games').doc(data.id)
.update({
playercount: newPlayerCountToString
})
.then(() => {
console.log(`COMPLETED UPDATE: ${JSON.stringify(res)}`);
res.send({
status: 200,
message: 'Game: updated.',
pin: gamePin
});
})
.catch(err => {
console.log(`ERROR IN QUERY: ${JSON.stringify(err)}`);
throw new Error(err);
});
} else {
console.log('could not find a match ', snapshot);
throw new Error('Error. could not find a match');
}
})
.catch(error => {
console.log(error);
res.status(500).send(error);
});
<小时/>

第二次更新,参见代码中的注释:

exports.addPlayerToGame = functions.https.onRequest((req, res) => {
return cors(req, res, () => {
// Check for POST request
if (req.method !== 'POST') {
res.status(400).send('Please send a POST request');
}

const gamePin = req.body.gamepin;
const numPlayers = req.body.playercount.toString();

admin //Here I would not use a getGame variable
.firestore()
.collection('games')
.where('gid', '==', gamePin)
.get()
.then(snapshot => {
if (!snapshot.empty) {
console.log(`BODY: ${JSON.stringify(req.body)}`);

const doc = snapshot.docs[0];
let data = doc.data();
data.id = doc.id;

const currentNumPlayers = data.playercount;
console.log(
`currentNumPlayers: ${JSON.stringify(currentNumPlayers)}`
);

const newPlayerCount = +numPlayers + +currentNumPlayers;
console.log(`newPlayerCount: ${JSON.stringify(newPlayerCount)}`);

const newPlayerCountToString = newPlayerCount.toString();
console.log(
`newPlayerCountToString: ${JSON.stringify(newPlayerCountToString)}`
);

return admin
.firestore()
.collection('games')
.doc(data.id)
.update({
playercount: newPlayerCountToString
})
.then(() => { //Here, I don't understand why do you return res. The update method returns an empty Promise so just do .then(() => {}}
console.log(`COMPLETED UPDATE`); //Here don't use res, as it is the Response object and represents the HTTP response that an Express app sends when it gets an HTTP request
res.send({
status: 200,
message: 'Game: updated.',
pin: gamePin
});
})
.catch(err => {
console.log(`ERROR IN QUERY: ${JSON.stringify(err)}`);
// throw new Error(err);
res.status(500).send(err); //I am not sure what is better... throwing an Error or sending back a 500 response code.
});
} else {
console.log('could not find a match ', snapshot);
res.send({ status: 400, message: 'Error. could not find a match' });
}

console.log(`END:`);
})
.catch(error => {
console.log(error);
res.status(500).send(error);
});
});
});

关于javascript - 谷歌云函数http触发foreach循环的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55962695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com