gpt4 book ai didi

javascript - 如何使用 Promise 将异步 Angular 函数的值返回到调用方法中?

转载 作者:行者123 更新时间:2023-12-02 16:54:50 25 4
gpt4 key购买 nike

我有一个填充了 for 循环的列表,我通过这种方式调用 assync 函数:

在我调用的 For 循环中

  row.SUCCES_RATE_SINCE = $scope.computeSuccessRateSinceStart(row);

被调用的函数

  // Calculate percentage of a whole from since
$scope.computeSuccessRateSinceStart = function(row) {

db = window.sqlitePlugin.openDatabase({name:"callplanner"});
// GET APPT COUNT
db.transaction(function(tx) {
tx.executeSql(sqlQuery, [], function(tx,results){
// init empty array for results
for (var i=0; i < results.rows.length; i++){
row = results.rows.item(i);
//Udpate date for writeout
//row.DATE = moment(row.DATE).format('ddd DD.M');
console.log("row APPT count is " + JSON.stringify(row));
apptCnt = row.APPT_CNT;
convCnt = row.CONVERS_CNT;
dailySuccessRateSince = apptCnt / convCnt * 100;
console.log("Success rate since is " +dailySuccessRateSince);
// THIS IS NOT WORKING
return Math.round(dailySuccessRateSince);

}
});
},function (e) {
console.log("ERROR: " + e.message);
$ionicLoading.show({
template: $translate.instant('ERROR_DATABASE'),
duration:1000
});
});

};

问题是计算值总是返回 null(返回函数在值在范围内可用之前执行)。

我对 Angular 还很陌生,但我发现这个问题可以使用 promise 来解决。有人能给我一个如何正确返回值的例子吗?

非常感谢您的帮助。

编辑:

现在触发了调用的方法,但我无法将返回值传递给变量,如下所示:

var test = $scope.computeSuccessRateSinceStart(row).then(function(result){
//ALERT WITH VALUE WORKS FINE
alert("Result " + result);
return result;
});
// THIS GIVES ME EMPTY ARRAY {}
alert("Result " + JSON.stringify(test));

最佳答案

为什么不让你的方法始终返回一个 promise ,然后从 promise 中提取结果?

$scope.computeSuccessRateSinceStart = function(row) {
var deferred = $q.defer();

db = window.sqlitePlugin.openDatabase({name:"callplanner"});
// GET APPT COUNT
db.transaction(function(tx) {
tx.executeSql(sqlQuery, [], function(tx,results){
// init empty array for results
for (var i=0; i < results.rows.length; i++){
row = results.rows.item(i);
//Udpate date for writeout
//row.DATE = moment(row.DATE).format('ddd DD.M');
console.log("row APPT count is " + JSON.stringify(row));
apptCnt = row.APPT_CNT;
convCnt = row.CONVERS_CNT;
dailySuccessRateSince = apptCnt / convCnt * 100;
console.log("Success rate since is " +dailySuccessRateSince);
// THIS IS NOW WORKING:
deferred.resolve(Math.round(dailySuccessRateSince));
}
});
}, function(e) {
console.log("ERROR: " + e.message);
deferred.reject(e);
});

return deferred.promise;
};

用法:

$scope.computeSuccessRateSinceStart(row).then(function(result){
// THIS GIVES THE VALUE:
alert("Result " + JSON.stringify(test));
return result;
}, function(e)
$ionicLoading.show({
template: $translate.instant('ERROR_DATABASE'),
duration:1000
});
});

关于javascript - 如何使用 Promise 将异步 Angular 函数的值返回到调用方法中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26256348/

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