Last active
September 10, 2018 23:22
-
-
Save LB-Digital/736839472eef9a9007469d99c0ad562e to your computer and use it in GitHub Desktop.
JS Chaining Promises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function myFunc(things, stuff){ | |
return new Promise( (resolve,reject) =>{ // setup | |
var result = []; | |
resolve(result); | |
}).then( (result) =>{ // Action 1 | |
return new Promise( (resolve,reject) =>{ | |
myFirstFunction(things,stuff) | |
.then(response => resolve(response)) | |
.catch(err => resolve([])); // nothing yet so return empty results array | |
}) | |
}).then( (results) =>{ // Action 2 | |
return new Promise( (resolve,reject) =>{ | |
mySecondFunction(things,stuff){ | |
.then(response =>{ | |
results = results.concat(response) | |
return resolve(results); | |
}) | |
.catch(err => resolve(results)); // nothing new so just return existing results | |
} | |
}); | |
}).then( (results) =>{ // Action 3 | |
return new Promise( (resolve,reject) =>{ | |
myThirdFunction(things,stuff) | |
.then(response =>{ | |
results = results.concat(response) | |
return resolve(results); | |
}) | |
.catch(err => resolve(results)); // nothing new so just return existing results | |
}) | |
}).then( (results) =>{ // Finalise response | |
return new Promise( (resolve,reject) =>{ | |
if (results.length == 0){ | |
return reject('nothing_found'); | |
}else{ | |
return resolve(results); | |
} | |
}) | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment