0

Needles to say I am doing something wrong. I need some help figuring out what it is.

Consider the following code (a simplified version of my problem):

function testTimer(time, msg,resolve){
console.log(arguments.callee.name);
window.setTimeout(
                function() {
                    console.log("MSG:", msg);
                    if(resolve !== undefined)
                        resolve(1);
                }, time * 1000);
}

new Promise(function(resolve, reject) {
    testTimer(1, 'ONE', resolve);
}).then(function(resolved){testTimer(9, 'TWO');}, function(rejected){alert("Rejected!", reject)})
.then(function(resolved){testTimer(1, 'THREE'); }, function(rejected){alert("Rejected!", reject)});

The expected output is:

ONE
TWO
THREE

Instead since the first then requires 9 seconds to execute and the second then requires 1 second to execute I get:

ONE
THREE
TWO

The question is simple: How can I get the then's to wait for eachother ?

Thanks!

Stanimirovv
  • 3,064
  • 8
  • 32
  • 56

1 Answers1

0

You need to return a promise that is resolved only after the time out fires:

function testTimer(time, msg,resolve) {
    console.log(arguments.callee.name);
    window.setTimeout(function() {
        console.log("MSG:", msg);
        if(resolve !== undefined) {
            resolve(1);
        }
    }, time * 1000);
}

new Promise(function(resolve, reject) {
        testTimer(1, 'ONE', resolve);
    }).then(
        function(resolved){
            // here we return a promise - that is resolved by testTimer
            // function. Notice that I'm passing a resolve function into it
            return new Promise(function(resolve) {
                testTimer(9, 'TWO', resolve);
            });
        },
        function(rejected){
            alert("Rejected!", reject)
        }
    )
    .then(
        function(resolved){testTimer(1, 'THREE'); },
        function(rejected){alert("Rejected!", reject)}
    );

How it works: testTimer function as you have defined it - accepts a callback as a 3rd argument that is to be invoked after the timer is fired. We employ that to resolve a nested promise that we set in the second step. So the third step is only happening after the second was resolved, which happens in the timer, so the order is kept as expected.

zerkms
  • 249,484
  • 69
  • 436
  • 539