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){
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();