Reputation: 201
I plan to use promise to solve some asynchronous issue in the app. In both promise I have some time consuming works to do. The simplified code is like this:
let connectServer = function () {
return new Promise(function (resolve, reject){
setTimeout(function (){
console.log("this is the 1st promise done!");
},50);
}); }
let connectFrontend = function (){
return new Promise(function (resolve, reject){
setTimeout(function (){
console.log("this is the 2nd promise done!");
},50);
}); }
connectServer().then(function (){
return connectFrontend();
}).then(function (){
console.log("finished coonectServer and returned the results to the frontend!");
}).catch(function () {
console.log("something wrong!")});
My intention is to run the first promise then run the 2nd(because the 2nd one will need use some results from the first one). Here it should print out "this is the 1st promise done!","this is the 2nd promise done!".
When I run this testing simplified code, it only print "the 1st promise done!" and then waiting... at the console. Nothing for long time until I have to use ctrl+c to come back to normal console/terminal. Means not run the 2nd promise.
What's wrong I am doing here?
Upvotes: 0
Views: 44
Reputation: 901
you are not resolving 1st and 2nd Promise :-
Just do it like this ->
let connectServer = function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("this is the 1st promise done!");
resolve("Result From 1st Promise");
}, 50);
});
};
let connectFrontend = function(from_1st) {
return new Promise(function(resolve, reject) {
console.log(from_1st);
setTimeout(function() {
console.log("this is the 2nd promise done!");
resolve("Result From 2nd Promise");
}, 50);
});
};
connectServer().then(function(result) {
return connectFrontend(result);
}).then(function(from_2nd) {
console.log(from_2nd);
console.log("finished coonectServer and returned the results to the frontend!");
}).catch(function() {
console.log("something wrong!");
});
Upvotes: 1