我在这里得到了4个承诺,我认为它会运行第一个,然后等到它完成,然后运行下一个,等到完成然后运行下一个等等。
但这里发生的是它一次性运行所有这些并且不等待任何事情完成。
这是我的承诺链:
//
// Run the promises
//
findBanks
.then(findReceipts)
.then(findExpenses)
.then(sendResult)
.catch(err => {
console.error(err);
console.log("getbankAccountReport ERR: " + err);
res.json({error:true,err})
});
这是我的console.log
的输出=====findAllBank=====
=====findAllReceipt=====
=====findAllExpense=====
=====RESOLVE findAllBank=====
=====sendResult=====
=====RESOLVE sendResult=====
=====RESOLVE findAllReceipt=====
=====RESOLVE findAllExpense=====
我不理解承诺是正确的还是?
无论如何这里是我的nodejs控制器:
exports.getBankAccountReport = function(req, res) {
//
// Find all bank accounts
//
var bankModel = require('../models/bankModel');
var bankTable = mongoose.model('bankModel');
var bankArray = [];
var findAllBank = new Promise(
(resolve, reject) => {
console.log("=====findAllBank=====")
bankTable.aggregate([
...lots of mongo stuff...
],function(err, data) {
if (!err) {
bankArray = data;
console.log("=====RESOLVE findAllBank=====")
resolve(data);
} else {
reject(new Error('findBank ERROR : ' + err));
}
});
});
//
// Find the RECEIPT for each bank account
//
var receiptModel = require('../models/receiptModel');
var receiptTable = mongoose.model('receiptModel');
var receiptArray = [];
var findAllReceipt = new Promise(
(resolve, reject) => {
console.log("=====findAllReceipt=====")
receiptTable.aggregate([
...lots of mongo stuff...
], function (err, data) {
if (!err) {
receiptArray = data;
console.log("=====RESOLVE findAllReceipt=====")
resolve(data);
} else {
reject(new Error('findReceipts ERROR : ' + err));
}
});
});
//
// Find the EXPENSE for each bank account
//
var expenseModel = require('../models/expenseModel');
var expenseTable = mongoose.model('expenseModel');
var expenseArray = [];
var findAllExpense = new Promise(
(resolve, reject) => {
console.log("=====findAllExpense=====")
expenseTable.aggregate([
...lots of mongo stuff...
], function (err, data) {
if (!err) {
expenseArray = data;
console.log("=====RESOLVE findAllExpense=====")
resolve(data);
} else {
reject(new Error('findExpense ERROR : ' + err));
}
});
});
var sendResult = function(data) {
var promise = new Promise(function(resolve, reject){
console.log("=====sendResult=====")
res.json({error:false,
"bank":bankArray,
"receipt":receiptArray,
"expense":expenseArray})
console.log("=====RESOLVE sendResult=====")
resolve();
});
return promise;
};
//
// Run the promises
//
findAllBank
.then(findAllReceipt)
.then(findAllExpense)
.then(sendResult)
.catch(err => {
console.error(err);
console.log("getbankAccountReport ERR: " + err);
res.json({error:true,err})
});
}
答案 0 :(得分:2)
您需要将Promise包装在函数中
var findAllBank = function() {
return new Promise(
(resolve, reject) => {
console.log("=====findAllBank=====")
bankTable.aggregate([
...lots of mongo stuff...
],function(err, data) {
if (!err) {
bankArray = data;
console.log("=====RESOLVE findAllBank=====")
resolve(data);
} else {
reject(new Error('findBank ERROR : ' + err));
}
});
});
});
解决后,将使用resolve()函数中传递的数据调用链中的下一个函数。
不要混淆Promise和构建它的函数
创建new Promise(executor)
时,您需要实现一个新对象,该对象将包含两个方法(对象的功能),.then(resolveCB [, rejectCB])
和.catch(rejectCB)
。
aime应该知道,无论何时完成一个过程,它是否成功或是否失败,并相应地继续。
var myFirstPromise = new Promise(function executor(resolve, reject) { resolve('resolved'); });
换句话说,一旦executor
定义的承诺得到解决,这些方法将用于继续您的流程。它可以获得fulfilled
并调用resolveCB
回调(使用then
)或rejected
并调用rejectCB
回调(同时使用then
和catch
)。回调(resolveCB或rejectCB)是一个函数,而不是Promise本身,即使回调函数可能返回Promise。
myFirstPromise
.then(function resolveCB(result) { console.log(result); }) //you can use a 2nd callback for rejection at this point
.catch(function rejectCB(err) { console.log(err); });
myFirstPromise
.then(
function resolveCB(result) { console.log(result); } // if resolved
, function rejectCB(err) { console.log(err); } // if rejected
)
.catch(function rejectCB(err) { console.log(err); }); // NEVER forget the last catch, just my 2cents :)
我们看到了.then()
和.catch()
的输入,但它们的返回值又如何呢?他们俩将返回一个新的承诺。这就是为什么你可以链接.then()
和.catch()
&#39>的原因。
myFirstPromise
.then(function resolveCB1(result) { console.log(result); })
.then(function resolveCB2(result) { console.log(result); }) // console.log is called but result is undefined
.catch(function rejectCB1(err) { console.log(err); });
myFirstPromise
.then(function resolveCB3(result) {
throw 'I threw an exception'; // an exception is thrown somewhere in the code
console.log(result);
})
.then(function resolveCB4(result) { console.log(result); })
.catch(function rejectCB2(err) { console.log(err); }); // a promise in the chain get rejected or error occured
在上一个示例中,我们看到第二个.then()
被点击但result
未定义。第一个.then()
返回的承诺已完整填充,但执行程序已将该值传递给解析回调resolveCB2
。在第二种情况下,resolveCB3
发生了异常,它被拒绝,因此调用了rejectCB2
。如果我们希望我们的解决回调接收参数,我们必须通知exector。为此,最简单的方法是使回调返回一个值:
myFirstPromise
.then(function resolveCB1(result) {
console.log(result);
result += ' again';
return result;
})
.then(function resolveCB2(result) {
console.log(result);
return result;
})
.catch(function rejectCB1(err) { console.log(err); });
现在他们说,你已经把所有的东西放在一起,以便了解Promise
。让我们尝试以更清洁的方式总结它:
var myFirstPromise = new Promise(function executor(resolve, reject) { resolve('resolved'); })
, resolveCB = function resolveCB(result) {
console.log(result);
result += ' again';
return result;
}
, resolveLastCB = function resolveLastCB(result) {
console.log(result);
result += ' and again';
return result;
}
, justLog = function justLog(result) {
console.log(result);
return result;
}
;
myFirstPromise
.then(resolveCB)
.then(resolveLastCB)
.then(justLog)
.catch(justLog);
你现在可以很好地表达它们,它很酷并且所有
myFirstPromise
.then(resolveCB)
.then(resolveCB)
.then(resolveCB)
.then(resolveCB)
.then(resolveCB)
.then(resolveCB)
.then(resolveLastCB)
.then(justLog)
.catch(justLog);
但是如果你的Promise连锁店确实如此'更改,您需要摆脱myFirstPromise
并从resolveCB
开始?它只是一个功能,可以执行,但没有任何.then()
或.catch()
方法。这不是承诺。你不能resolveCB.then(resolveLastCB)
,它会发生错误解决。然后(不是一个函数或类似的东西。你可能认为这是一个严重错误,我没有调用{{1} }和resolveCB
应该有效吗?对于那些想到这一点的人来说,它仍然是错误的。resolveCB().then(resolveLastCB)
会返回一个字符串,一些字符,而不是resolveCB
。
为了避免这种维护问题,您应该知道resolve和reject回调可以返回Promise
而不是值。为此,我们将使用所谓的工厂模式。简单来说,工厂模式是使用(静态)函数实现新对象,而不是直接使用构造函数。
Promise
迭代数组时,工厂函数可能会派上用场。它可能用于在给定输入的情况下生成一个promise数组:
var myFirstPromiseFactory = function myFirstPromiseFactory() {
/*
return new Promise(function executor(resolve, reject) {
resolve('resolved');
});
if you just need to resolve a Promise, this is a quicker way
*/
return Promise.resolve('resolved');
}
, resolveFactory = function resolveFactory(result) {
return new Promise(function executor(resolve, reject) {
result = result || 'I started the chain';
console.log(result);
result += ' again';
return resolve(result); // you can avoid the return keyword if you want, I use it as a matter of readability
})
}
, resolveLastFactory = function resolveLastFactory(result) {
return new Promise(function executor(resolve, reject) {
console.log(result);
result += ' and again';
return resolve(result);
});
}
, justLogFactory = function justLogFactory(result) {
return new Promise(function executor(resolve, reject) {
console.log(result);
return resolve(result);
});
}
;
myFirstPromiseFactory() //!\\ notice I call the function so it returns a new Promise, previously we started directly with a Promise
.then(resolveFactory)
.then(resolveLastFactory)
.then(justLogFactory)
.catch(justLogFactory);
// Now you can switch easily, just call the first one
resolveFactory()
.then(resolveLastFactory)
.then(justLogFactory)
.catch(justLogFactory);
justLogFactory('I understand Javascript')
.then(resolveLastFactory)
.then(justLogFactory)
.catch(justLogFactory);