简体   繁体   中英

Converting call back to async/await functions

I'm trying to concert a callback function to stand chained functions, but could not manage it,

the callback function is:

db.transaction(
 function(t){
  t.executeSql("SELECT * FROM cal_list where calories > ?" ,[min_cal_amount], function(t,r){
     for (var i=0; i < r.rows.length; i++){
      food = r.rows.item(i).food;
      amount_of_calories = r.rows.item(i).amount_of_calories;
      serving_size = r.rows.item(i).serving_size;           
        
      list.innerHTML +="<li>"+food+" has "+amount_of_calories+" KCAL worth of calories.</li>";
                    
        }
    }, 
            
    function(t,e){alert(e.message);})
}
);

How can I convert to to async..await or try..then..catch ?

If your database library exposes db.transaction and t.executeSQL in a promise based api, it would look roughly like this:

const transaction = await db.transaction();

try {
    const result = await transaction.executSql(
        'SELECT * FROM cal_list where calories > ?',
        [min_cal_amount]
    );

    for (var i = 0; i < result.rows.length; i++) {
        // work with result data
    }
}
catch (e) {
    // rollback transaction, handle error as appropriate
}

If your library does not expose those functions in a promise based api, you can use util.promisify to wrap those functions that expect a callback, and then use the above snippet.

What you can do is "promisify" db.transaction to return you a promise.

function asyncTransaction(sql, params) {
    return new Promise((resolve, reject) => {
        db.transaction(function(t) {
            t.executeSql(sql, params, (t, rows) => resolve(rows), (t, error) => reject(error))
        })
    })
}

At this point you have a wrapper of db.transaction that you can consume as

try {
  const rows = await asyncTransaction('SELECT * FROM cal_list where calories > ?', [min_cal_amount])

  // ...
} catch (err) {
  alert(err.message);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM