Javascript 理解承诺

myT*_*532 0 javascript

我一直在使用 NodeJS 异步,但我试图了解 JavaScript 中的基本承诺,但我遇到了问题。

我创建了下面的代码进行测试。

function first() {
  // Simulate a code delay
  return new Promise(function(resolve) {
    setTimeout(function() {
      console.log(1);
    }, 500);
  });
}

function second() {
  console.log(2);
}

first().then(second());
Run Code Online (Sandbox Code Playgroud)

它应该首先打印“1”,但它首先在控制台中打印“2”。为什么会发生?

谢谢

ray*_*eld 6

两件事情:

first().then(second())second() 立即调用并将其返回值作为参数传递给then。你想传入函数本身,而不是它的返回值:

first().then(second); // no parens on second


你永远不会解决第一个承诺:

return new Promise(function(resolve) {
  setTimeout(function() {
      console.log(1);
      resolve(); // <--  without this the promise is never resolved
    }, 500);
  }
);
Run Code Online (Sandbox Code Playgroud)

解决了这些问题后,它会按您的预期工作:

function first() {
  // Simulate a code delay
  return new Promise(function(resolve) {
    setTimeout(function() {
      console.log(1);
      resolve(); // <--  without this the promise is never resolved
    }, 500);
  });
}

function second() {
  console.log(2);
}

first().then(second);
Run Code Online (Sandbox Code Playgroud)