简体   繁体   English

将回调转换为异步/等待函数

[英]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 ?如何转换为async..awaittry..then..catch

If your database library exposes db.transaction and t.executeSQL in a promise based api, it would look roughly like this:如果您的数据库库在基于t.executeSQL的 api 中公开db.transactiont.executeSQL ,它大致如下所示:

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.如果你的库没有在基于util.promisify的 api 中公开这些函数,你可以使用util.promisify来包装那些需要回调的函数,然后使用上面的代码片段。

What you can do is "promisify" db.transaction to return you a promise.你可以做的是“promisify” db.transaction来给你一个承诺。

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在这一点上,您有一个db.transaction的包装器,您可以将其用作

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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