JavaScript的承诺链 – 为什么不工作?
在下面的代码中,有人可以解释为什么在Promise链中调用secondMethod()
工作,但调用secondMethod()
不?
function firstMethod() { return new Promise(function(resolve, reject){ setTimeout(function() { console.log('first method completed'); resolve(); }, 2000); }); }; function secondMethod() { return new Promise(function(resolve, reject){ setTimeout(function() { console.log('second method completed'); resolve(); }, 2000); }); }; function thirdMethod() { return new Promise(function(resolve, reject){ setTimeout(function() { console.log('third method completed'); resolve(); }, 3000); }); }; // Works firstMethod().then(secondMethod).then(thirdMethod); // Doesn't work - executes secondMethod immediately after firstMethod // firstMethod().then(secondMethod()).then(thirdMethod);
因为Promise.then
需要一个或两个callback。 它没有承诺。
当你立刻打电话给secondMethod
你传递了一个承诺。
它基本上是这样做的:
firstMethod() .then(new Promise(...)) // Should be a function, not a Promise
第二种方法不起作用,因为在任何超时解决之前,以同步的方式立即调用函数。
这是另一种思考发生了什么的方法:
// you're calling all your methods and creating promises before creating the chain let first = firstMethod(); let second = secondMethod(); let third = thirdMethod(); first.then(second).then(third);