Nativescript异步函数返回对象Promise

时间:2019-02-20 10:21:00

标签: javascript sqlite promise nativescript nativescript-plugin

我是异步新手,正在等待语法。我编写了一个函数,以在本机脚本中返回由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
}

2 个答案:

答案 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();
}