我正在使用 nano-promise 尝试强制 node.js 中的以下代码串联运行。但是,在第一个 CouchDB 插入完成之前,以下承诺似乎仍然完成。这会导致一个问题,因为后面的 Promise 将包含查询 CouchDB 的代码,并期望前面步骤中的代码是完整的。我相信这个问题是因为在 db.get 之后和 db.get 完成之前立即执行 return 。有没有人对如何解决这个问题有任何建议?
var nano = require('nano')('http://localhost:5984');
var Promise = require('nano-promise');
var db = nano.db.use('myDB');
var promise = new Promise(function (resolve, reject) {
resolve(request);
}).then(function (args) {
console.log('step 1');
console.log(args.body);
db.get(args.body.id, function(err, body) {
var doc_update = body;
if (!err) {
doc_update.beginDate = args.body.startDate;
doc_update.updated = new Date();
db.insert(doc_update, args.body.id, function(err, body){
if(!err){
console.log('Database UPDATED (Step 1)');
}
});
} else {
doc_update.updated = new Date();
db.insert(doc_update, args.body.id, function(err, body){
if (err) throw err;
});
}
});
return new Promise.Arguments(args);
}).then(function (args) {
console.log(args.body);
return new Promise.Arguments(args);
});
promise.then(function (args) {
console.log(args.body);
return new Promise.Arguments(args);
});
promise.then(function (args) {
console.log(args.body);
});
这段代码的输出是:
step 1
{id: '123',
startDate: '2017-12'}
step 2
{id: '123',
startDate: '2017-12'}
step 3
{id: '123',
startDate: '2017-12'}
step 4
{id: '123',
startDate: '2017-12'}
Database UPDATED (Step 1)
输出应该是:
step 1
{id: '123',
startDate: '2017-12'}
Database UPDATED (Step 1)
step 2
{id: '123',
startDate: '2017-12'}
step 3
{id: '123',
startDate: '2017-12'}
step 4
{id: '123',
startDate: '2017-12'}