为了在最近潜入节点后进行实验,我编写了一个简单的promise代码,然后从命令行执行它。我看到了两种输出。这是我的代码:
function doWork(){
return new Promise(function(resolve,reject){
setTimeout(function(){
console.log('done!');
resolve();
}, 1000);
});
}
然后:
1. doWork().then(function(){
return doWork();
}).then(function(){
console.log('that\'s it');
});
Output :
done!
done!
that's it!
另一种方式:
2. doWork().then(function(){
doWork();
}).then(function(){
console.log('that\'s it');
});
Output:
done!
that's it!
done!
为什么在我没有return
或我return
时输出会发生变化?
答案 0 :(得分:2)
承诺按返回值工作。当你没有Layer
时,链不知道在继续链中的下一个处理程序之前等待第二个internalMethod()
。
答案 1 :(得分:1)
基本上,你通过不从成功处理程序返回来破坏承诺链。
doWork().then(function () {
// this will be executed only after first call to doWork is resolved.
// When this executes it returns the promise returned by doWork thereby asking next then handler to wait till this promise is resolved.
return doWork();
}).then(function () {
// since we are returning doWork second call promise, this will be executed only after it is resolved.
// if we don't return doWork second call promise, it won't wait for promise to be resolved and directly execute.
console.log('that\'s it');
});