我用node.js实现了以下代码,我想知道为什么调用writeToDB但是第一次没有在数据库中插入数据。
uploadInfoObject = {
ProcessId: pid,
Type: "type",
ModifiedDate: new Date(),
Status: "Started",
Message: "Processing Started"
};
writeToDB(uploadInfoObject);
console.log('File Downloaded! ' + data.ContentType);
var exec = require('child_process').exec,
child;
child = exec('gs -sDEVICE=jpeg -dTextAlphaBits=4 -r300 -o /tmp/%d.jpeg ' + stored_pdf, function(error, stdout, stderr) {
uploadInfoObject = {
ProcessId: Processid,
Type: "Ticket",
ModifiedDate: new Date(),
Status: "Processing",
Message: "Splitting into pages done"
}
writeToDB(uploadInfoObject); //this gets called but data is not there in the db
});
writeToDB Funciton
function writeToDB(infoObject) {
dbService.connectDb(config.DB_CONFIG.CONNECTIONSTRING, {})
.then(() => {
return dbService.insert(infoModel(dbService), infoObject);
})
.then(data => dbService.disconnectDb(data))
.then(data => console.log("success"))
.catch((error) => {
dbService.disconnectDb(error).then(error => {
console.log(error);
})
});
}
请帮忙
答案 0 :(得分:1)
首先,从writeToDB返回一个Promise,然后将writeToDB(uploadInfoObject)
之后的代码包装在.then中,就像这样
uploadInfoObject = {
ProcessId: Processid,
Type: "Ticket",
ModifiedDate: new Date(),
Status: "Started",
Message: "Processing Started"
};
writeToDB(uploadInfoObject)
// wrap in .then
.then(() => {
console.log('File Downloaded! ' + data.ContentType);
var exec = require('child_process').exec;
exec('gs -sDEVICE=jpeg -dTextAlphaBits=4 -r300 -o /tmp/%d.jpeg ' + stored_pdf, function(error, stdout, stderr) {
uploadInfoObject = {
ProcessId: Processid,
Type: "Ticket",
ModifiedDate: new Date(),
Status: "Processing",
Message: "Splitting into pages done"
}
writeToDB(uploadInfoObject); //this gets called but data is not there in the db
});
});
function writeToDB(infoObject) {
// add return so a promise is returned
return dbService.connectDb(config.DB_CONFIG.CONNECTIONSTRING, {})
.then(() => dbService.insert(infoModel(dbService), infoObject))
.then(data => dbService.disconnectDb(data))
.then(data => console.log("success"))
.catch((error) => {
dbService.disconnectDb(error).then(() => {
// throw the original error, otherwise .then will be called!
throw error;
})
});
}
注意:你的writeToDB函数有一个缺陷,它捕获错误,但随后处理它 - 任何调用该函数的代码都将继续.then
- 因此抛出断开连接。然后回调