[英]Promises and Order of Operations
抱歉,这是一个基本概念。 我是Java的新手。
我试图了解以下功能的执行顺序。 之后,我设置了一个带有2个回调的Promise和一个带有3个回调的Promise。
function getSum(n1, n2){
var isAnyNegative = function() {
return n1<0 || n2 < 0;
}
var promise = new Promise(function(resolve, reject) {
if (isAnyNegative()){
reject(Error('Negative not supported'));
}
resolve(n1 + n2)
});
return promise;
}
// Double Promise
getSum(5,6).then(function(result) {
console.log('DL1 '+result);
return getSum(10,20);
}, function(error){
console.log(error);
}).then(function(result) {
console.log('DL2 '+result);
}, function(error){
console.log(error);
});
// Triple Promise
getSum(5,6).then(function(result) {
console.log('TL1 '+result);
return getSum(10,20);
}, function(error){
console.log(error);
}).then(function(result){
console.log('TL2 '+result);
return getSum(30,40);
}, function(error){
console.log(error);
}).then(function(result){
console.log('TL3 ' +result);
}, function(error){
console.log(error);
});
输出如下(DL =>双层,TL =>三层):
DL1 11
TL1 11
DL2 30
TL2 30
TL3 70
期望输出是双层然后是三层,但是事实并非如此。 我研究了吊装,但据我了解,它至少应该保护脚本中的执行顺序。 这些函数如何排序,为什么不按出现顺序执行?
如果需要更多详细信息,请先向“道歉”和“谢谢”提出问题。
当运行Promise时,每个.then
处理程序都会异步运行,如https://javascript.info/microtask-queue所述
基本上对于您的代码来说,这意味着
如果您真的需要诺言先解决DL,然后再解决TL,则需要使它们成为同一诺言链的一部分
您的示例中的执行顺序是正确的。
当涉及异步操作(Promises)时,整个概念与同步操作有所不同。
在下面的说明中,您可以将Promise假定为运行操作的计划/队列。
例如,使用以下简化代码:
function sum(a, b){ return new Promise(function(resolve, reject){ if (a < 0 || b < 0) reject(new Error('Negative not supported.')); else resolve(a + b); }); } /* Double layer */ sum(5, 6).then(function(result){ console.log('DL1', result); return sum(10, 20); }).then(function(result){ console.log('DL2', result); }).catch(function(error){ console.error(error); }); /* Triple layer */ sum(5, 6).then(function(result){ console.log('TL1', result); return sum(10, 20); }).then(function(result){ console.log('TL2', result); return sum(30, 40); }).then(function(result){ console.log('TL3', result); }).catch(function(error){ console.error(error); });
如果我们按照上面的示例,执行队列将类似于:
sum
。 sum(5, 6)
作为DL运行。 sum
(DL)的执行结束。 sum(5, 6)
作为TL运行。 Promise DL在后台运行。 sum
(TL)的执行结束。 Promise DL在后台解决。 .then()
。在后台解决了Promise TL。 .then()
。DL1在后台解决。 .then()
。在后台解决了Promise TL1。 如您所见,使用Promises,一些操作在后台运行。 这就是为什么您会看到执行顺序可能看起来不一样的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.