我是异步新手,正在等待语法。我编写了一个函数,以在本机脚本中返回由SQLite查询的promise给出的值,但是当写入控制台时,返回值是[object promise]。 代码如下
async function counterChanger(database) {
await database.all("SELECT * FROM pets").then(function (rows) {
for (row in rows) {
// console.log(rows[row]);
counter += 1;//counter is a global variable
}
return counter;
}).then(function (counter) {
counterValue = counter; //counterValue is a global variable initialized to 0
})
console.log("Outside db counterValue is ", counterValue); //meanwhile the console displays the actual value of ounterValue
return counterValue; // the output is [Object promise] instead of the value of counterValue
}
答案 0 :(得分:0)
我认为您在内联函数之前缺少异步功能。试试这个:
$scope.worklevel = [
{ lvlid: 1, lvlnm: 'First Level' },
{ lvlid: 2, lvlnm: 'Second Level' }
]
$scope.newassignment = function () {
$scope.wrklevel2 = {};
angular.forEach($scope.departments, function (d) {
d.details = false;
})
}
答案 1 :(得分:0)
async/await
的全部目的是避免应许链。如果有可能发生错误,则必须用try/catch
块包装等待代码,并且它总是返回Promise
,因此对async
函数的调用也应使用await
关键字
async function counterChanger(database) {
try {
// returning length of returned rows
return (await database.all("SELECT * FROM pets")).length;
} catch(e) {
// just in case if an error thrown for whatever reason, can be handled / logged here
}
// would return `0` if there was an error
return 0;
}
async function updateCounterValue() {
counterValue = await counterChanger();
}