Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
i want to run "setVal" function Completed after then that "afterFirstFunc" function will go to execute,

var setVal = function() {
var dfd=$.Deferred();
for (var i = 0; i < 5; i++) {
(function (i) {
setTimeout(function () {
console.log("Inside First "+i);
}, 1000*i);
})(i);
};
dfd.resolve();
return dfd.promise();
};
var setVal1=function(){
var dfd1=$.Deferred();
for (var i = 0; i < 5; i++) {
(function (i) {
setTimeout(function () {
console.log("Inside Second "+i);
}, 1000*i);
})(i);
};
dfd1.resolve();
return dfd1.promise();
};
setVal().then(function(){
setVal1(); 
});


What I have tried:

i want to execute setVal1 run first then setVal1 will go to execute, not both the function work parallel, i have tried all the thing but nothing help me to achieve this
Posted
Updated 5-Sep-18 8:08am

1 solution

You resolve the promise returned from setVal before any of the setTimeout calls have executed.

You need to wait until all of the setTimeout calls have completed before resolving the promise. You'll want to create a separate promise for each call, and use Promise.all[^] to wait for them all to complete.
JavaScript
var delay = function(time, value){
    return new Promise(function(resolve) {
        setTimeout(resolve.bind(null, value), time);
    });
};

Promise.prototype.delay = function(time) {
    return this.then(function(value) {
        return delay(time, value);
    });
};

var setVal = function(){
    var promises = [];
    for (var i = 0; i < 5; i++){
        promises.push(Promise.resolve(i).delay(i * 1000).then(function(i){
            console.log("Inside first", i);
        }));
    }
    
    return Promise.all(promises);
};

var setVal1 = function(){
    var promises = [];
    for (var i = 0; i < 5; i++){
        promises.push(Promise.resolve(i).delay(i * 1000).then(function(i){
            console.log("Inside second", i);
        }));
    }
    
    return Promise.all(promises);
};

setVal().then(setVal1);

javascript - using setTimeout on promise chain - Stack Overflow[^]
Promise - JavaScript | MDN[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900