承诺在以不同方式执行时显示不同的结果

Promises when executed differently displaying different results

本文关键字:显示 结果 方式 承诺 执行      更新时间:2023-09-26

在最近深入节点后,我只是为了进行实验,编写了一个简单的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时输出会发生变化?

通过返回值承诺工作。如果没有return,则链不知道在继续到链中的下一个处理程序之前要等待第二个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');
});