你如何阻止承诺,然后进入下一个函数?

时间:2016-05-27 11:46:09

标签: javascript

我是承诺的新手,我觉得这应该是一件非常简单的事情。

如果变量返回true,我希望下面的代码停在第一个then

           if (groupCodes.length === 1) {
                // Get all does not populate the group object so it will just be the identifier as we require
                var groupIdentifier = groupCodes[0].group;

                GroupMember
                .nestedCreate({ groupId: groupIdentifier, type: groupCodes[0].type }, { })
                .$promise
                .then(function (group) {
                    var isUserAlreadyInGroup = _.includes(group, user._id);
                    if (isUserAlreadyInGroup) {
                        // If this variable returns true I would like to preent the below then function from running
                        notify.info('You have already joined ' + scope.groupCode);
                    }
                })
                .then(function () {
                    // Now that we have joined the group, we have permission
                    // to access the group data.
                    return Group
                        .getById({ groupId: groupIdentifier })
                        .$promise;
                })
           }

2 个答案:

答案 0 :(得分:1)

根据您对我的问题的回答,如果您使用的诺言库没有提供您想要的方法,您可以随时让第二个then成为有条件调用的单独函数来自第一个then函数。

首先,将第二个then定义为单独的函数。

var secondThen = function(groupIdentifier) {
  // Now that we have joined the group, we have permission
  // to access the group data.
  return Group
    .getById({
      groupId: groupIdentifier
    })
    .$promise;
};

以下是您的示例中使用我的建议的then代码段。

.then(function(group) {
    var isUserAlreadyInGroup = _.includes(group, user._id);
    if (isUserAlreadyInGroup) {
      notify.info('You have already joined ' + scope.groupCode);
    } else {
      // I'm not sure where `groupIdentifier` comes from, I assume you can figure that out, since you had it in your code
      secondThen(groupIdentifier);
    }
})

答案 1 :(得分:0)

试试这个:

if (groupCodes.length === 1) {
    // Get all does not populate the group object so it will just be the identifier as we require
    var groupIdentifier = groupCodes[0].group;

    GroupMember
     .nestedCreate({ groupId: groupIdentifier, type: groupCodes[0].type }, { })
     .$promise
     .then(function (group) {
         var isUserAlreadyInGroup = _.includes(group, user._id);
         if (isUserAlreadyInGroup) {
             // If this variable returns true I would like to preent the below then function from running
             notify.info('You have already joined ' + scope.groupCode);
         }

         return isUserAlreadyInGroup;
     })
     .then(function (isUserAlreadyInGroup) {
         if (!isUserAlreadyInGroup) {
             // Now that we have joined the group, we have permission
             // to access the group data.
             return Group
              .getById({ groupId: groupIdentifier })
              .$promise;
             });
         })
     }