How to make a chained file with pure Javascript?

Asked

Viewed 444 times

2

How to make a dazed call with Javascript native Promise?

I mean, I would like the sentence below to be executed one after the other and I would like to know when that sequence of Promises is finalized.

var promise;

console.log('iniciando...');

[1, 2, 3, 4, 5].forEach(function (i) {

    promise = new Promise(function (resolve) {
        setTimeout(function () {
          resolve(i);
        }, 1000)
    });
    
    
    promise.then(function (value) {
         console.log(value);
    });
});

console.log('finalizado');

  • 1

    You had to make a veiled advertisement for Bolsonaro, right? Wow, this one has to be genius to understand, I wouldn’t understand if it wasn’t for me that I came up with :D

  • 1

    This question is not duplicated from the other https://answall.com/q/140814/129 ?

  • @Sergio can hammer :p, now that I have seen that they are similar

1 answer

1


I saw a solution for this in Angularjs. I adapted this solution to native Javascript.

See the code below:

var promise = Promise.resolve();

console.log('iniciando...');

[1, 2, 3, 4, 5].forEach((i) => {

    promise = promise.then(function () {
        console.log(i);
        return new Promise(function (resolve) {
            setTimeout(function () { resolve(i) }, 1000)
        })
    })

});


promise.then(function (value) {
   console.log('finalizando');
});

If you see observe the code, we start an already solved file and use the method then, which, in turn, returns another History. When we do this, the method then can be set to solve the problem returned in then previous.

For example:

 promiseA.then(function () {
    return promiseB;
 }).then(function () {
     return promiseC;
 })

All the secret in the forEach above is summarized in matching the variable promise defined externally to the result of the template created in the iteration.

When we call the President after the forEach, will cause the result of then is solved only after the last iteration has been solved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.