我正在尝试理解 Promise。但在这里我很困惑。 我想创建一个测试函数,在 3 秒后打印 3000,然后在 2 秒后打印 2000,然后在 1 秒后打印 1000。这是我的代码:
'use strict';
var Q = require('q');
function delayConsole(timeOut) {
var defer = Q.defer();
setTimeout(function(){
console.log(timeOut);
defer.resolve(2000);
},timeOut);
return defer.promise;
}
// This works
delayConsole(3000).then(function(){
return delayConsole(2000);
}).then(function(){
return delayConsole(1000);
});
// This doesn't work. Why?
delayConsole(3000).then(delayConsole(2000)).then(delayConsole(1000));
最佳答案
在那里,您立即调用函数delayConsole
:
.then(delayConsole(2000))
也就是说:您不传递函数,而是传递函数调用的结果,您不等待 promise 被链接。
当你这样做
then(function(){
return delayConsole(2000);
})
然后你传递一个函数,而不是该函数调用的结果。当 Promise 链中的前一个元素被解决时,可以调用该函数。
关于javascript - 有人可以帮我解释一下下面的代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26095626/