then运行的Promise方法在Promise完成之前

Promise method of then running before Promise is completed

在下面的例子中,Promise 完成并打印了 aaa 之后,那么应该只打印 hello。但是,它没有发生。为什么,因为 .then 方法仅在 Promise 完成后运行。

function printF(item){
  return new Promise((resolve, reject) => resolve(setTimeout(function(){console.log('aaa')}, 1000)));
}

printF(10).then(res => console.log('hello'));

如果因为你正在立即解决你的承诺,即在承诺内部调用 setTimeout,那么承诺将立即解决触发 .then 部分,然后在 1 秒后 setTimeout 代码将被执行。

相反,resolve 承诺在 1 秒后将 resolve 包装在 setTimeout 内作为 -

function printF(item) {
  return new Promise((resolve, reject) =>
    setTimeout(() => resolve(console.log('aaa')), 1000)
  );
}

printF(10).then(res => console.log('hello'));