在 for 循环中跳出 promise 块 [英] Break out of promise block in a for loop

查看:45
本文介绍了在 for 循环中跳出 promise 块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码 -

this.storeNameValidate = function(stores) {
    var deferred = $q.defer();

    console.log(stores);
    for (storeIndex in stores) {
        this.nameValidate(stores[storeIndex].storeName, 3, 10)
            .then(function() {
                console.log("valid store name");
            }, function() {
                console.log("invalid store name");
                deferred.reject("invalid store name");
            })
    }
    return deferred.promise;
}

如果 nameValidate 错误块被调用,我需要中断 for 循环.我怎样才能做到这一点 ?

I need to break out off the for loop if the nameValidate error block is called. How can i do this ?

我可以使用标记来做这样的事情

I can do it something like this using flagging

this.storeNameValidate = function(stores) {
    var deferred = $q.defer();
    var flag = false;
    console.log(stores);
    for (storeIndex in stores) {
        this.nameValidate(stores[storeIndex].storeName, 3, 10)
            .then(function() {
                console.log("valid store name");
                var flag = true;
            }, function() {
                var flag = false;
                console.log("invalid store name");
                deferred.reject("invalid store name");
            })
            if (!flag)break;
    }
    return deferred.promise;
}

他们有更好的方法吗?

推荐答案

你应该使用 $q.all 带有承诺数组并返回组合承诺.如果其中一个内部承诺失败,这个单一承诺将被拒绝.

You should use $q.all with array of promises and return combined promise. This single promise will reject if one of the inner promises fails.

this.storeNameValidate = function (stores) {

    var promises = Object.keys(stores).map(function(storeIndex) {
        return this.nameValidate(stores[storeIndex].storeName, 3, 10).then(function () {
            console.log("valid store name");
        }, function () {
            return $q.reject("invalid store name");
        });
    }, this);

    return $q.all(promises);

};

另外,不要滥用 $q.defer 你不需要它在你的情况下.这种多余的用法被称为延迟反模式.

Also, don't abuse $q.defer you don't need it in your case. Such a redundant usage of it is known as deferred anti-pattern.

此外,如果您要拒绝的错误消息始终是无效的商店名称"(不是特定于商店的)并且您实际上不需要对已验证的商店执行其他操作,则可以一起省略错误和成功回调也.然后代码会变得更干净:

Also, if error message you are going to reject with is always "invalid store name" (not store specific) and you don't really need to preform additional actions on validated stores, you can omit error and success callbacks all together too. Then the code will become even cleaner:

this.storeNameValidate = function (stores) {

    var promises = Object.keys(stores).map(function(storeIndex) {
        return this.nameValidate(stores[storeIndex].storeName, 3, 10);
    }, this);

    return $q.all(promises);

};

这篇关于在 for 循环中跳出 promise 块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆