带有promise / async-await的callback上下文
我正在尝试使用ES7的asynchronous等待function,以避免在我的一些代码中的callback地狱。 我正在使用SQLite,我需要在callback的上下文中访问一个variables。
为了说明,这里是从sqlite3 npm模块:
module.exports = function() { db.run("INSERT INTO foo ...", function(err) { // err is null if insertion was successful console.log("inserted id:", this.lastID); }); };
假设我创build了一个承诺运行上面的代码,我怎样才能访问this.lastID
与asynchronous等待function?
module.exports = async function() { try { await db.run("INSERT INTO foo ..."); // How can I access the `this` context? } catch (err) { } };
你可以定义一个聪明的prom.ified版本的db.run
:
db.runAsync = function(query) { return new Promise((resolve, reject) => this.run(query, function (err) { if (err) { reject(err) } else { resolve(this) } })) }
然后,您将能够使用此runAsync
从您的asynchronous等待代码访问this
上下文:
let res = await db.runAsync('INSERT INTO foo ...') console.log(`inserted id: ${res.lastID}`)