Асинхронная функция Nativescript, возвращающая обещание объекта

Я новичок в синтаксисе async и await. Я написал функцию, возвращающую значение, данное обещанием запроса SQLite в собственном скрипте, но возвращаемое значение - [обещание объекта] при записи в консоль. Код идет ниже

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
}

person calebdeji    schedule 20.02.2019    source источник


Ответы (2)


Я думаю, вам не хватает async перед встроенной функцией. Попробуй это:

async function counterChanger(database) {
    await database.all("SELECT * FROM pets").then(async 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
}

person Hamed Afshar    schedule 20.02.2019

Вся цель 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();
}
person Manoj    schedule 20.02.2019