下面是我的调度器,我正在从firebase数据库中读取数据,并通过调用receiptValidationRequest(key, receiptData, date)
更新数据。在这个函数中,我尝试从对apple的HTTP调用的响应中检索验证数据,但它不能正常工作。有时它会起作用,一些数据会更新。我不确定为什么会发生这种情况,也不知道我在这里遗漏了什么。
exports.updateDatabaseScheduler = functions.pubsub.schedule('0 0 */3 * *').onRun(async context => {
console.log('scheduler started');
await ref.on('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
console.log(i++ + " : " +childSnapshot.key);
receiptValidationRequest(childSnapshot.key, childData['ReceiptData'], myDate);
});
});
console.log('scheduler finished');
});
async function receiptValidationRequest(userID, receiptData, myDate){
let password = 'my password';
try{
const data = JSON.stringify({
'receipt-data': receiptData,
'password' : password,
'exclude-old-transactions': false
});
const options = {
resolveWithFullResponse: true,
// hostname: 'sandbox.itunes.apple.com',
hostname: 'buy.itunes.apple.com',
port: 443,
path: '/verifyReceipt',
method: 'POST',
json: true,
headers: {
'Content-Type': 'application/json',
// 'Content-Length': data.length
}
};
const req = await https.request(options,res => {
myStatusCode[0] = res.statusCode;
let expireDate = [];
let transactionId = [];
var trialPeriod = [];
var body = '';
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
body = body + d;
// console.log("body : "+body);
});
res.on("end", () => {
body = JSON.parse(body);
let array = Object.keys(body);
console.log("body : "+body);
//parsing data here
insertIntoDB(userID, expireDate, transactionId, trialPeriod, myDate);
});
});
req.write(data);
req.end();
}catch(e){
req.on('error', (error) => {
console.error(error)
});
}
}
发布于 2020-01-07 00:36:21
你需要使用return a promise that resolves when all of the asynchronous work is complete。如果没有它,Cloud Functions就不知道何时关闭函数是安全的。你现在所面临的是一个竞争条件--有时在云功能关闭之前工作是必须的,但并非总是如此。
我建议研究另一个HTTP库,它可以更容易地处理承诺,比如“请求-承诺”。
发布于 2020-01-06 18:36:53
receiptValidationRequest
是异步functioN。在forEach
中调用时,您没有等待。此外,请使用for..of
或promise.all
而不是forEach
,因为forEach
不能在循环中使用promises。
https://stackoverflow.com/questions/59610359
复制相似问题