Search code examples
javascriptnode.jsasync-awaitpromiseecmascript-2016

Callback context with promise/async-await


I am trying to use the ES7 async-await feature to avoid callback hell in some of my code. I am using SQLite and I need to access a variable in the context of the callback.

To illustrate, here is the thing, from the sqlite3 npm module:

module.exports = function() {
  db.run("INSERT INTO foo ...", function(err) {
    // err is null if insertion was successful
    console.log("inserted id:", this.lastID);
  });
};

Let's assume I created a promise running the above code, how can I access the this.lastID with the async-await feature?

module.exports = async function() {
  try {
    await db.run("INSERT INTO foo ...");
    // How can I access the `this` context?
  } catch (err) {
  }
};

Solution

  • You could define a smart promisified version of db.run:

    db.runAsync = function(query) {
      return new Promise((resolve, reject) => this.run(query, function (err) {
        if (err) {
          reject(err)
        } else {
          resolve(this)
        }
      }))
    }
    

    Then you'll be able to use this runAsync to access this context from your async-await code:

    let res = await db.runAsync('INSERT INTO foo ...')
    console.log(`inserted id: ${res.lastID}`)