Learning promises, does not execute sequentially

4

I am learning promises , and I was doing some examples.

This is my code in which I intend to show.

  

the following: // one, two, three, four but instead shows   asynchronously // one, four, two, three

let promise =new Promise(function(resolve,reject){
    console.log("uno");
    resolve();
});
promise.then(function(){
    console.log("dos");
    console.log("tres");
});
console.log("cuatro");
    
asked by hubman 30.10.2016 в 17:01
source

2 answers

3

The promises are scheduled for a next moment. The exact moment in which the functions are to be executed does not depend on you. You can only indicate the order of execution, not the exact moment.

If you want to show "asynchronously" one, two, three four:

new Promise(resolve => {
    console.log('uno');
    resolve();
}).then(_ => {
  console.log('dos');
  console.log('tres');
}).then(_ => {
  console.log('cuatro');
}).catch(err => {
  console.log(err);
});

On the other hand, then returns a promise. You also have the catch() "above". It is much simpler. You can, then, chain a then after another, what they return is a promise. If at any time there is a throw , then the catch method is executed.

    
answered by 30.10.2016 / 17:49
source
2

With what objective? Is it just to learn? I would say that it would be better not to use promises, since it is just that, that they appear without apparent order, that is, asynchronous.

I would try this:

var array=["uno","dos","tres","cuatro"]
for(var i=0;i<array.length;i++)
{
    console.log(array[i]);
}

... or more simply, console.log(" uno \n dos \n tres \n cuatro")

Another way would be to make a setTimeOut that calls another setTimeout until the end of the cycle.

    
answered by 30.10.2016 в 17:51