-1

In the below code why promise.then() behaves asynchronously. In other words , why browser is not waiting for the code written inside promise.then() method to be executed?.What tell the browser engine so that promise.then() makes an asynchronous call?

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');

The above code prints the output in the below order, which means promise.then() works asynchronously.

  • Before
  • After
  • Success You have a car!
user3742125
  • 617
  • 2
  • 9
  • 31

1 Answers1

2

Promise is asynchronous

You can use await like this to make synchronous

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');

To get result

Before
Success You have a car!
After
Tung Duong
  • 1,156
  • 7
  • 19
  • but there is no event loop like how it is being used for setTimeout function. If you execute the code here - latentflip.com/loupe/ you could see no event loop is running. I was under the assumption that there is an event loop behind every asynchronous call. – user3742125 Sep 27 '18 at 15:31