Conditional promise?

35 views
Skip to first unread message

Kevin Burton

unread,
Jan 14, 2016, 12:13:51 PM1/14/16
to Q Continuum (JavaScript)
I have an issue that seems to me like it almost might be some kind of pattern.
I have a spot in the chain that looks like:

return Promise.all(fieldRows.map(function(fieldRow) {
var autoFillGroupRequest = new sql.Request();
var autoFillGroupQuery = 'select *' +
' from [EForms].[OnlineForm].[AutoFillGroup] ag' +
' where ag.formDefinitionID = ' + formRow.formDefinitionID + ' and ' +
' ag.displayFieldKey = \'' + fieldRow.fieldKey + '\'';
return autoFillGroupRequest.query(autoFillGroupQuery).then(function(autoFillGroupRow) {
var autoFillRuleRequest = new sql.Request();
var autoFillRuleQuery = 'select *' +
' from [EForms].[OnlineForm].[AutoFillRule] ar' +
' where ar.autoFillRuleGroupID = ' + autoFillGroupRow.autoFillRuleGroupID+ ' and ' +
' ag.destinationFieldKey = \'' + fieldRow.fieldKey + '\'';
return autoFillRuleRequest.query(autoFillRuleQuery).then(function(autoFillRuleRow) {

});

The problem is that it is possibly (and even likely) that the section in yellow may not need to execute. In other words the 'autoFillRow' that is resolved in the 'then' could be null so the query in yellow can't and need not be formed. But, I want to continue the chain. If the code in yellow can be executed then I will 'resolve' it by continuing the chain and returning another Promise. If the code in yellow doesn't get run I also want to return the next Promise in the chain which is the same Promise that would be executed if the code in yellow was not executed. But I don't want to duplicate code. So pseudo-code looks like:

    return autoFillGroupRequest.query(autoFillGroupQuery).then(function(autoFillGroupRow) {
        if(autoFillGroupRow) {
var autoFillRuleRequest = new sql.Request();
var autoFillRuleQuery = 'select *' +
' from [EForms].[OnlineForm].[AutoFillRule] ar' +
' where ar.autoFillRuleGroupID = ' + autoFillGroupRow.autoFillRuleGroupID+ ' and ' +
' ag.destinationFieldKey = \'' + fieldRow.fieldKey + '\'';
return autoFillRuleRequest.query(autoFillRuleQuery).then(function(autoFillRuleRow) {
return new Promise(resolve, reject).then(function(next) {
                });
});
        } else {
                return new Promise(resolve, reject).then(function(next) {
                });
       }


So is there a pattern to do this kind of thing without having to brute force like I have done in the pseudo-code above?

Thank you.

Kevin
Reply all
Reply to author
Forward
0 new messages