I'm encountering issues with implementing promises in JavaScript.
There are 3 asynchronous functions that rely on each other:
The functions are named func1, func2, and func3 respectively.
- func1 produces a single result that func2 requires.
- func2 also generates a single result.
- func3 relies on results from both func1 and func2.
As a consequence, func3 needs to wait for the completion of both func1 and func2, while func2 only waits for func1.
Although I managed to create a working JS fiddle, dealing with the combined usage of all three functions is quite messy. What would be the best approach to handle this chained operation effectively?
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);
});
}
// The function calls chaining
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);
});