In node js how to control asynchronous programming

0

If for example I have two lists of numbers and letters.

 var arrayletras = ["a","b","c","d","e"];
var arrayNum = [1,2,3,4];

arrayletras.forEach(function (valLetras) {
    console.log(valLetras+": ");
    arrayNum.forEach(function (valNum) {
        setTimeout(function () {
            console.log(valNum);
        },1000)
    })
})

I want to show a letter first and then all the numbers. I have read about callbacks and promises, but I have not just solved this problem

    
asked by Ezio 11.07.2017 в 18:44
source

1 answer

1

The problem of setTimeout is that it simply adds the callback to the dispatcher, then follows its course, ie it does not wait for the callback to be completed.

Instead you should use asynchronous functions, and wait for await to execute a Promise

var arrayLetras = ["a","b","c","d","e"];
var arrayNum = [1,2,3,4];

function sleep(ms)
{
  return new Promise(resolve => { setTimeout(resolve,ms) })
}

async function recorrer(){ 
  for (let letra of arrayLetras) 
    {
      console.log(letra)
      for (let numero of arrayNum)
        {
          console.log(numero)
          await sleep(1000)
        }
    }
}

recorrer()

For more information
1. async
2. await
3. Promise

    
answered by 11.07.2017 / 20:55
source