首页 > 解决方案 > 我收到重复的结果,因为 nodejs 在发送 200 响应之前就将其判断为发送失败

问题描述

当应用参与奖励事件时,奖励服务器将结果发送到应用服务器。如果没有 200 响应,奖励公司服务器会在一定时间内重复发送结果。

如果应用服务器没有响应 200,奖励服务器会重复发送结果。

所有获得的积分都会被记录下来。检查是否有带有事件ID的点记录,如果没有点记录,记录点并以200响应。问题是即使在第一个200响应之前,就判断为传输失败,结果再次发送,因此具有相同事件 ID 的多个点正在累积。

我该怎么办?有没有办法在应用服务器上处理这个问题?

db.collection('pointHistory').doc(uid).collection('pointHistory').add(newPointHistory).then(ref => {
                    db.collection('users').doc(uid).update({point: addTotalPoint});
                    db.collection('offerwallHistory').doc(uid).collection('offerwallHistory').add(offerwallHistory_data);
                    db.collection('adminPointHistory').add(adminPointHistory_data);
                    setDailyPointStatus(reward, 12);
                    setOtherPersonalPointStatus(reward, uid, "dailyPersonalPointStatus");
                    setOtherPersonalPointStatus(reward, uid, "weeklyPersonalPointStatus");
                    setOtherPersonalPointStatus(reward, uid, "monthlyPersonalPointStatus");
                    return res.send(event_id + ":OK").status(200);
                }).catch(err => {
                    console.log(err);
                    return null;
                });
                return res.send(event_id + ":OK").status(200);

标签: node.jsfirebasegoogle-cloud-firestoreironsource

解决方案


是的,你做错了。您使用的 promise(then/catch) 不会等待所有过程完成。您应该尝试了解更多有关 async / await 的信息,以使您的代码更清晰易读,并且您可以像刚才一样使用它,但没有返回 return res.send(event_id + ":OK").status(200); 在末尾。例如:

try {
  await db.collection('pointHistory').doc(uid).collection('pointHistory').add(newPointHistory)
  await db.collection('users').doc(uid).update({point: addTotalPoint});
  db.collection('offerwallHistory').doc(uid).collection('offerwallHistory').add(offerwallHistory_data);
  db.collection('adminPointHistory').add(adminPointHistory_data);
  setDailyPointStatus(reward, 12);
  setOtherPersonalPointStatus(reward, uid, "dailyPersonalPointStatus");
  setOtherPersonalPointStatus(reward, uid, "weeklyPersonalPointStatus");
  setOtherPersonalPointStatus(reward, uid, "monthlyPersonalPointStatus");
  return res.send(event_id + ":OK").status(200);
} catch(error) {
  return null; 
}

您需要像这样包装函数:

async function myFunc() {}

推荐阅读