JS ES6 Promise Chaining

I am trying to learn how to use promises, but I have problems understanding the chain. I assume that both promises will be executed with this code. Then, when I call test.then (), it should know that the test has resolved and pass then () permission data.

As soon as this function ends, it moves on to the next, then (), repeating the same process with the promise test2.

However, I can only get it to print the results of the first promise, not the second. Any ideas what's missing here?

var test = new Promise(function(resolve, reject){
    resolve('done1');
});

var test2 = new Promise(function(resolve, reject){
    resolve('done2');
});

test
.then(function(data) {
    console.log(data);
})
.then(test2)
.then(function(data) {
    console.log(data);
});
+4
source share
4 answers

. then call undefined, . then . :

var test = new Promise(function(resolve, reject){
    resolve('done1');
});

var test2 = new Promise(function(resolve, reject){
    resolve('done2');
});

test
.then(function(data) {
    console.log(data);
    return test2;
})

.then(resultOfTest2 => doSomething)
.then(function(data) {
console.log(data);
});
+10

then:

test.then(function(data) {
    console.log(data);
    return test2;
}).then(function(data) {
    console.log(data);
});
+3

you need to return another promise (test2) in the first promise (test1) to provide the chain:

  var test = new Promise(function(resolve, reject){
    resolve('done1');
});

var test2 = new Promise(function(resolve, reject){
    resolve('done2');
});

test
.then(function(data) {
  console.log(data);
  return test2;
});
+2
source

You can also try -

    let test = new Promise(function(resolve, reject){
        resolve('done1');
    });

    let test2 = new Promise(function(resolve, reject){
        resolve('done2');
    });

    try {
        let logOne = test();
        let logTwo = test2();
        console.log(logOne);
        console.log(logTwo);
    } catch(error) {
        console.error(error);
    }

That way, you can also properly handle any promise dependencies. For example, if the test was based on two test data, you could -

try {
        let logOne = test();
        let logTwo = test2(logOne);
        console.log(logOne);
        console.log(logTwo);
    } catch(error) {
        console.error(error);
    }
0
source

All Articles