【问题标题】:Why promise.then() behaves asynchronously? [duplicate]为什么 promise.then() 的行为是异步的? [复制]
【发布时间】:2018-09-27 15:15:06
【问题描述】:

在下面的代码中,为什么promise.then() 的行为是异步的。换句话说,为什么浏览器不等待写在promise.then()方法中的代码被执行?告诉浏览器引擎是什么让promise.then()进行异步调用?

const money = 500;

let promise = new Promise(function(resolve,reject){
    if(money > 400){
        resolve('You have a car!');
    }else{
        reject('Yo do not have enough money to buy the Car!');
    }
});
console.log('Before');
promise.then(function(data){
    console.log('Success '+data);
});
console.log('After');

上面的代码按以下顺序打印输出,这意味着 promise.then() 异步工作。

  • 之前
  • 之后
  • 成功你有车了!

【问题讨论】:

  • JavaScript 是单线程的,then() 中的回调函数优先排队。
  • Promise 应该是异步的。您可以通过await 命令强制他们等待。
  • promise.then 就是这么做的。
  • 但是没有像 setTimeout 函数那样使用事件循环。

标签: javascript es6-promise


【解决方案1】:

Promise 是异步的

你可以像这样使用await来同步

const money = 500;

let promise = new Promise(function(resolve,reject){
    if(money > 400){
        resolve('You have a car!');
    }else{
        reject('Yo do not have enough money to buy the Car!');
    }
});
console.log('Before');

let data = await promise
console.log('Success '+data);
console.log('After');

得到结果

Before
Success You have a car!
After

【讨论】:

  • 但是没有事件循环像它被用于 setTimeout 函数。如果您在此处执行代码 - latentflip.com/loupe/,您可能会看到没有事件循环正在运行。我假设每个异步调用背后都有一个事件循环。
猜你喜欢
  • 2020-04-20
  • 1970-01-01
  • 2019-06-07
  • 2019-06-05
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多