Promise chain with setTimeout

clock icon

asked 7 months ago

message

1 Answers

eye

33 Views

I'm a freshman in javascript, and now learning the Promise part.

Below I've been trying to write a promise chain with setTimeout, and expect it to print "first result" after 2 seconds, and print "second result" after another 2 seconds. However, it prints "first result" and "second result" at the same time.

Can anyone tell me where did I make a mistake?

var doSomething = new Promise(function(resolve,reject){ 
    setTimeout(function(){ 
        resolve('first result');  
    },2000); 
});

var doSomethingElse = new Promise(function(resolve,reject){ 
    setTimeout(function(){
        resolve('second result');  
    },2000); 
});

doSomething
    .then(function(result){
    console.log("This is the "+result); 
    return doSomethingElse;
    })
    .then(function(result){
        console.log("This is the "+result);
});

============================

EDIT: So when I write promise as below, the executor function(setTimeout) starts counting immediately, and become resolved after 2 seconds.

var doSomething = new Promise(function(resolve,reject){   // starts counting here
    setTimeout(function(){ 
        resolve('first result');  
    },2000); 
});

However, if I wrap the promise inside a function as below, the executor function (setTimeout) starts counting only after I call the function. Is this correct?

function doSomething(){
    return new Promise(function(resolve,reject){
        setTimeout(function(){
            resolve('first result');
        },2000);
    })
}
doSomething(); // starts counting here

1 Answers

You are creating a promise and assigning it to doSomething. The first timer starts counting down.

Then you immediately create another promise and assign it to doSomethingElse. The second timer starts counting down.


Create the second promise after the first one has resolved.

Write your answer for this question.

Top Questions