gpt4 book ai didi

node.js - nodejs sqlite3 db.run 作为 Bluebird promise

转载 作者:搜寻专家 更新时间:2023-10-31 23:34:57 24 4
gpt4 key购买 nike

我正在尝试在 Express 应用程序中使用 sqlite3。基本上,我收到一个休息请求,根据休息请求,我查询一个外部 REST 请求。在来自外部请求的响应和从原始 REST 请求传入的数据之间,我执行更新或插入到我的一个 sqlite3 表中。

我遇到的问题是,在 db.run(sqlStatement, paramArray, function(err)) 中,function(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-sqlite3 代码,我很确定它在成功的回调函数中返回 this 的方式,而不是作为实际参数, 是问题。这意味着即使尝试使用 bluebird 的 multiArgs=true 参数也没有用,因为没有正确的返回值。

所以我尝试将 db.run 函数包装在我自己的自定义 promise 方法中,这似乎成功了。

具体来说,我做了:

function runCustomAsync(sql, params) {
return new Promise(function(resolve, reject) {
db.run(sql, params, function cb(err) {
if(err) {
var responseObj = {
'error': err
}
reject(responseObj);
} else {
var responseObj = {
'statement': this
}
resolve(responseObj);
}
});
});
}

db.runCustomAsync = runCustomAsync;
module.exports = db;

这与通常的处理方式略有不同。我现在返回的对象可能包含 this 对象,也可能包含 err 对象。

按照我原来的要求,我现在做

db.runCustomAsync(sqlStatement, params)
.then(function(dbResponseObj) {
if(dbResponseObj.error) {
//handle error
} else {
//do stuff with dbResponseObj.statement
}
})

关于node.js - nodejs sqlite3 db.run 作为 Bluebird promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36111106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com