I’m looking for a way to create a promise chain that has forks. By “forks” I mean the chain could go in two or more different directions depending on some condition. For example:
getIndexes(searchString).then(indexes => {
if (indexes.length) return searchByIndex(indexes, 1, 5);
else return searchAllRecords(searchString);
}.then(records => {
// if searched all records
return createIndexes(records, searchString);
// else
return records;
}).then( // how to handle multiple forks
As you can see, there are conditions in each then
block and depending on the condition, it will return something different to the next then
block by calling different functions. So we don’t know what each then
block will receive as it depends on the outcomes of the previous conditions, and we have to do checks to see how it should be handled. This doesn’t seem ideal. What is the best way to build a promise chain when it contains forks in the flow?