Javascript writeToDB函数只执行一次
我用node.js实现了以下代码,我想知道为什么会调用writeToDB,但在第一次之后数据不会插入到DB中Javascript writeToDB函数只执行一次,javascript,node.js,Javascript,Node.js,我用node.js实现了以下代码,我想知道为什么会调用writeToDB,但在第一次之后数据不会插入到DB中 uploadInfoObject = { ProcessId: pid, Type: "type", ModifiedDate: new Date(), Status: "Started", Message: "Processing Started" }; writeToDB(uploadInfoObject); console.log('File
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函数
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);
})
});
}
请帮助首先,返回writeToDB的承诺,然后将代码包装在a中的writeToDB(uploadInfoObject)之后。然后,像这样
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函数有一个缺陷,它捕获错误,然后再处理它-任何调用函数的代码都将继续执行
。然后
不管如何-因此会出现断开连接。然后回调您的代码不太容易阅读-您是否考虑过适当的缩进?writeToDB
是异步的-我猜这是一个错误issue@JaromandaX我签了合同我怎么能等待,然后执行next,因为我必须在大多数地方使用该方法。你能展示一个采样器吗?从writeToDB
-转换承诺并使用writeToDB(uploadInfoObject)。然后(…函数中的其余代码像其他任何代码一样在这里。然后链)
非常感谢,一个简单的问题,如果我反复使用相同的方法,我应该使用然后在其中添加其余的代码吗?异步代码就是这样使用的。。。哦,我对writeToDB catch做了一个更改-在回答中解释