简体   繁体   English

为什么javascript中.then()里面的Promise同时被执行?

[英]Why does Promise inside .then() in javascript gets executed at the same time?

        const promise1 = new Promise(function(resolve, reject) {
          setTimeout(function() {
            resolve('promise1');
          }, 3000);
        });

        const promise2 = new Promise(function(resolve, reject) {
          setTimeout(function() {
            resolve('promise2');
          }, 3000);
        });

        promise2.then(function(value) {
          console.log(value);
          promise1.then(function(value) {
              console.log(value);
            });
        });

output: *after 3 seconds, both displays at the same time输出:*3秒后,同时显示

promise2 promise1承诺2 承诺1

What i'm expecting is, after 3 seconds, promise2 will be displayed first then after another 3 seconds, promise1 will be displayed because promise1 should only execute after the console log in promise2 .then().我期望的是,3 秒后,promise2 将首先显示,然后再过 3 秒,promise1 将显示,因为 promise1 只应在控制台登录 promise2 .then() 后执行。

Promises are eager in evaluation, you can make them lazy by wrapping them in a Function. Promises 在求值时很急切,您可以通过将它们包装在函数中来使它们变得懒惰。

 const promise1 = () => new Promise(function(resolve, reject) { setTimeout(function() { resolve('promise1'); }, 3000); }); const promise2 = () => new Promise(function(resolve, reject) { setTimeout(function() { resolve('promise2'); }, 3000); }); promise2() .then(console.log) .then(() => promise1()) .then(console.log)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM