gpt4 book ai didi

javascript - 解析云函数-按顺序执行的代码

转载 作者:行者123 更新时间:2023-12-03 02:35:14 26 4
gpt4 key购买 nike

如果满足某些条件,并且在 for 循环结束时,我有以下函数来更新行,响应包括更新了多少行。尽管更新了超过零行,但响应显示为零。查看日志,似乎 reponse.success() 在完成 for 循环之前触发。

为什么会这样?

Parse.Cloud.define("reset", function(request, response) {


var isSaveNeeded = false
var Query = new Parse.Query("price");
Query.equalTo('isActive', true);
Query.find({useMasterKey:true})
.then((results) => {
console.log("Found " + results.length + " price rows")
var currentDate = moment()
var noOfRowsUpdated = 0
for (let i = 0; i < results.length; ++i) {
var valid_till_date = results[i].get('valid_till_date');

if (valid_till_date == null) {
// if user had not selected valid_till_date then set to expire after system max no of days
var updatedAt = results[i].get('updatedAt');
if (currentDate.diff(updatedAt,'days') > 10) {
console.log("Permanent change row to be set inactive. Updated at - " + currentDate.diff(updatedAt)+ updatedAt)
results[i].set('isActive',false)
isSaveNeeded = true
}
} else if (currentDate.diff(valid_till_date) > 0) {
// check whether valid_till_date has passed
console.log("Found row with elapsed valid date " + results[i].id)
results[i].set("isActive",false)
isSaveNeeded = true
}
if (isSaveNeeded == true) {
console.log("Record needs to be saved for " + results[i].id)
results[i].save(null, {useMasterKey:true})
.then(function (user) {
++noOfRowsUpdated
console.log("reset : Object ID: " + results[i].id + " saved - " + noOfRowsUpdated)
})
.catch(function (error) {
console.log("reset : Error saving Object ID: " + results[i].id + error);
response.error(error);
})
} else {

console.log("Record not to be saved for " + results[i].id)
}
isSaveNeeded = false
} // end of for loop
//BELOW IS EXECUTED BEFORE FOR LOOP COMPLETES
console.log("Updated " + noOfRowsUpdated +" price rows");
response.success("Updated " + noOfRowsUpdated +" price rows")
}) // end of .then((results)
.catch(function(error) {
response.error("Failed to fetch from price" + error );
});
});

最佳答案

Parse.com 的 save 运行异步,因此循环在保存发生之前完成。解决方案是稍微重新组织一下代码,并等待保存发生后再执行响应函数。

诀窍是收集数组中每个保存返回的 promise ,并使用 Promise.when() (Promise.all() 的同义词)等待这些 promise 的履行

为了更清楚地说明,去掉“是否需要保存”逻辑,因此这个云函数只能用于处理数据库......

Parse.Cloud.define("reset", function(request, response) {
var Query = new Parse.Query("price");
Query.equalTo('isActive', true);
Query.find({useMasterKey:true}).then((results) => {
console.log("Found " + results.length + " price rows");
// assuming ES6 or something like underscore
let pricesToSave = results.filter(price => priceNeedsSave(price));

// here's the important part, collect the promise from each save
// proceed only after the promises have completed
let promises = pricesToSave.map(price => price.save(null, {useMasterKey:true}));
return Parse.Promise.when(promises).then(() => pricesToSave.length);
}).then(count => {
response.success("Updated " + count +" price rows");
}).catch(error => {
response.error("Failed to fetch from price" + error );
});
}

为了完整起见,下面是分解出的 needSave 逻辑。 (OP应该检查一下,我刚刚复制了循环体)...

function priceNeedsSave(price) {
var isSaveNeeded = false;
var currentDate = moment()

var valid_till_date = price.get('valid_till_date');
if (valid_till_date == null) {
// if user had not selected valid_till_date then set to expire after system max no of days
var updatedAt = price.get('updatedAt');
if (currentDate.diff(updatedAt,'days') > 10) {
console.log("Permanent change row to be set inactive. Updated at - " + currentDate.diff(updatedAt)+ updatedAt)
price.set('isActive',false)
isSaveNeeded = true
}
} else if (currentDate.diff(valid_till_date) > 0) {
// check whether valid_till_date has passed
console.log("Found row with elapsed valid date " + price.id)
price.set("isActive",false)
isSaveNeeded = true
}
return isSaveNeeded;
}

关于javascript - 解析云函数-按顺序执行的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48561675/

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