How to make a promise linked with pure Javascript? [duplicate]

2

How to make a dazzling call with the native Javascript promise?

I mean, I would like the sentence below to be executed one after the other and that I could know when this sequence of promises are 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');
    
asked by anonymous 12.06.2018 / 20:23

1 answer

1

I've seen a solution to this in AngularJs. I have adapted this solution for 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 the code, we start an already resolved promise and use the then method, which in turn returns another promise. When we do this, the then method can be dazzled to resolve the promise returned in then previous.

For example:

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

All the secret in% w / w% above is summed to match the% w_% variable set externally to the result of the wording created in the iteration.

When we call the promise after forEach , it will cause the result of promise to be resolved only after the promise of the last iteration is resolved.

    
12.06.2018 / 20:23