为什么在添加Promise代码时此代码会立即执行?

时间:2018-02-14 20:10:06

标签: javascript promise settimeout

在下面的代码中,我预计会有两个4秒的延迟。但是如果你运行代码,你会看到它立即执行。显然我不明白一些非常基本的东西,或者我是一个我看不到的愚蠢错误。

function calculatesomething(resolve) {
  console.log("calculating");

  setTimeout(results(resolve,3),4000);
}

var answer=0;
function results(resolve,n) {
  console.log("got results");

  answer=1;
  resolve(answer+n);
}



function doingstuff() {
  console.log("starting");

  var promise1 = new Promise(function(resolve) {
    setTimeout(calculatesomething(resolve),4000);
  });

  promise1.then(function(value) {
    console.log("done: "+value);
  });

  console.log("regular execution");
}

doingstuff();

(抱歉这里有缩进。我不知道为什么它不尊重标签。)

2 个答案:

答案 0 :(得分:6)

最根本的是:

 setTimeout(results(resolve,3),4000);

您不需要直接调用函数并传递返回的值,而是传递函数引用:

 setTimeout(results, 4000, /*args:*/ resolve, 4);

答案 1 :(得分:1)

setTimeout接受一个回调函数作为第一个参数,其中一个可能的解决方案是将函数调用包装在一个匿名函数中,如下所示:

function calculatesomething(resolve) {
  console.log("calculating");

  setTimeout(function() {
    results(resolve,3);
  }, 4000)
}

var answer=0;
function results(resolve,n) {
  console.log("got results");

  answer=1;
  resolve(answer+n);
}



function doingstuff() {
  console.log("starting");

  var promise1 = new Promise(function(resolve) {
    setTimeout(function() {
      calculatesomething(resolve)
    }, 4000);
  });

  promise1.then(function(value) {
    console.log("done: "+value);
  });
        
  console.log("regular execution");
}

doingstuff();