Javascript 不同执行时的承诺显示不同的结果

Javascript 不同执行时的承诺显示不同的结果,javascript,node.js,callback,promise,Javascript,Node.js,Callback,Promise,为了在最近深入到node之后进行实验,我编写了一个简单的promise代码,然后从命令行执行它。我看到了两种输出。这是我的密码: function doWork(){ return new Promise(function(resolve,reject){ setTimeout(function(){ console.log('done!'); resolve(); }, 1000); }); }

为了在最近深入到node之后进行实验,我编写了一个简单的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!

当我不
返回
或当我执行
返回
时,为什么输出会更改?

承诺通过返回值工作。当您不返回时,链不知道在继续执行链中的下一个处理程序之前等待第二个
doWork

承诺按返回值工作。当您不返回时,链不知道在继续到链中的下一个处理程序之前等待第二个
doWork

基本上,您违反了承诺链,没有从成功处理程序返回它

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');
});

基本上,你打破了承诺链,没有从成功处理者那里返回它

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');
});

return保留链,而您不启动新的未连接链。return保留链,而您不启动新的未连接链。我的问题是,如果它断开链,那么为什么它在打印
后再次返回?因为链已经断开了?对
doWork()
的调用并没有消失在遗忘中,它仍然存在,但“就是它”
then()
(你应该命名你的函数,更好的解释)不会等待它完成。代码不会返回,而是异步如何与javascript一起工作。@nickB它只是一个函数调用-函数调用被执行,日志-返回承诺的函数被调用-但它只知道通过返回值“等待”。我的问题是,如果它打破了链,那么为什么它在打印
后再次返回?因为链已经断开了?对
doWork()
的调用并没有消失在遗忘中,它仍然存在,但“就是它”
then()
(你应该命名你的函数,更好的解释)不会等待它完成。代码不会返回,而是异步如何与javascript一起工作。@nickB它只是一个函数调用-函数调用被执行,日志-返回承诺的函数被调用-但它只知道通过返回值“等待”。