为什么promise.then()行为异步?

时间:2018-09-27 15:15:06

标签: javascript es6-promise

在以下代码中,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()是异步工作的。

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

1 个答案:

答案 0 :(得分:2)

承诺是异步的

您可以使用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