Home > Software design >  Incorrect value after calling promise async function in js
Incorrect value after calling promise async function in js

Time:08-24

I'm trying to make a function that checks how many records in database and sends the number to variable:

var records = -1;

async function howManyRecords() {
    let myPromise = new Promise(function (resolve) {

        DB.transaction(function (tx) {
            tx.executeSql('SELECT count(*) AS mycount FROM DemoTable', [], function (tx, rs) {
                records = rs.rows.item(0).mycount;
                resolve();
            },);
        });
    });
    await myPromise;
    console.log("records from promise function: "   records);
    return myPromise;
}

Then I would like to use the number in another functions, for example display in the console log when device is ready:

onDeviceReady.then(function () {
    howManyRecords();
    console.log("after calling function records are: "   records);
}

The howManyRecords function counts records correctly, but then variable records is not correct:

IMG: after calling function records are: -1 // records from promise function: 5

I really need some help, I'm new to the topic and stuck here since a long time and can't go on. I'm using cordova sqlite.

CodePudding user response:

Try this:

onDeviceReady.then(async function () {
await howManyRecords();
console.log("after calling function records are: "   records);}

CodePudding user response:

This problem is not for your asynchronous behavior. Here actually you re assign the value of records variable in the function. That's why the value of records change. If you want to get rid of from the issue you can take another variable in the function for counting records. And initialize the variable with let. As let is block scope, that's why its' value will not go through the function.

var records = -1;

async function howManyRecords() {
    let records = -1;

    let myPromise = new Promise(function (resolve) {

        DB.transaction(function (tx) {
            tx.executeSql('SELECT count(*) AS mycount FROM DemoTable', [], function (tx, rs) {
                records = rs.rows.item(0).mycount;
                resolve();
            },);
        });
    });
    await myPromise;
    console.log("records from promise function: "   records);
    return myPromise;
}

  • Related