Javascript 如何阻止一个先承诺后功能进入下一个后承诺功能?
我对承诺不熟悉,我觉得这应该是一件很简单的事情 如果变量返回true,我希望下面的代码首先停止Javascript 如何阻止一个先承诺后功能进入下一个后承诺功能?,javascript,Javascript,我对承诺不熟悉,我觉得这应该是一件很简单的事情 如果变量返回true,我希望下面的代码首先停止,然后停止: if (groupCodes.length === 1) { // Get all does not populate the group object so it will just be the identifier as we require var groupIdentifier = groupC
,然后停止
:
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;
})
}
试试这个:
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;
});
})
}
根据您对我的问题的回答,如果您正在使用的promise库没有提供您想要的方法,那么您可以始终让第二个
然后
成为一个单独的函数,从第一个然后
函数有条件地调用该函数
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;
};
首先,将第二个定义为一个单独的函数
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);
}
})
从第一个然后是方法返回一个值。在第二个中询问该值,然后
确定是否应该继续。你用什么来兑现承诺?所问的问题实际上是一个骗局,但这种情况下的解决方案比复杂的承诺炼金术简单得多。。。。只需使用if-else语句合并这两个函数