【发布时间】:2016-07-06 18:50:48
【问题描述】:
我正在尝试在 express 应用中使用 sqlite3。 基本上,我得到一个休息请求,根据休息请求,我查询一个外部 REST 请求。在来自外部请求的响应和从原始 REST 请求传入的数据之间,然后我进行更新或插入到我的一个 sqlite3 表中。
我遇到的问题是,在db.run(sqlStatement, paramArray, function(err)) 中,函数(err) 是一个回调,其中err 要么是错误,要么是nil。除此之外,如果err 参数是null,那么this 引用包含2 个属性,其中一个告诉我语句修改的行数。 (https://github.com/mapbox/node-sqlite3/wiki/API#databaserunsql-param--callback供参考)
问题是,我在 sqlite3 模块上运行 bluebird 的 promisifyAll,然后使用结果
db.runAsync(sqlStatement, paramArray).then(err) {
console.log(this) //results in a null
}
所以我无法确定是否有任何更新。
我的整个代码部分看起来有点像这样:
function handleRequest(req, res) {
//this returns the response as the first object
request.getAsync('http://www.example.com', reqObj)
.then(prepareDbObjects) //prepares an array of objects to update the DB with
.then(attemptUpdate)
.then(function(rowsUpdated) {
res.json(rowsUpdated)
}
}
function attemptUpdate(updateObjs) {
var promiseMap = Promise.map(updateObjs, function(singleObj) {
return updateOrInsertObj(singleObj)
}
return promiseMap
}
function updateOrInsertObj(singleObj) {
return db.runAsync(sqlStatement, singleObj)
.then(function(err) {
if(err) {
//handle error
} else {
console.log("this should be an object with 2 properties", this)
//but instead it is null
}
}
}
【问题讨论】:
标签: node.js sqlite promise bluebird