I am failing to use promises properly in JS from what it seems like.
I have 3 async inter-dependent functions, like so:
func1, func2 and func 3.
- func1 returns a single results that func2 uses.
- func2 returns a single result as well
- func3 uses results from func1 and func2.
So func3 has to wait for both func1 and 2, while func2 has to wait for only func1.
Here is the JS fiddle that I was able to compose and it works, but reading the mess where the 3 are used together is just a nighmare. What would be a proper way to execute such a chain operation?
function func1() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(10);
}, 1000);
});
}
function func2(return1) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(return1 + 20);
}, 1000);
});
}
function func3(val1, val2) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(val1 + val2);
}, 1000);
});
}
func1().then(function(result) {
func2(result).then(function(result2) {
func3(result, result2).then(function(finalResult) {
console.log(finalResult);
}, function(err) {
console.log(err);
});
});
}).catch(function(err) {
console.log(err);
});