【问题标题】:Promise method of then running before Promise is completed [duplicate]在 Promise 完成之前运行的 Promise 方法[重复]
【发布时间】:2021-03-28 22:33:02
【问题描述】:

在下面的例子中,在 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'));

【问题讨论】:

  • 在问题的当前形式中,显示的代码解析然后调用给定的 then 方法,我认为所提出的问题对于任何当前的实现都不可能......也许请查阅文档:@987654321 @

标签: javascript ecmascript-6 es6-promise


【解决方案1】:

如果因为你正在立即解决你的承诺,即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'));

【讨论】:

    猜你喜欢
    • 2017-03-05
    • 2019-03-07
    • 2023-01-27
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 2019-03-31
    相关资源
    最近更新 更多