javascript - 这种情况适合 $q 吗?

标签 javascript angularjs

我无法确定是否应该将 $q 用于以下伪编码场景:

function create() {

    if (condition1) {
        // ajax call that needs to update
        // the object to be passed into Service.create()
    }

    if (condition2) {
        // ajax call that doesn't make updates to object
    }

    Service.create(object).success(function() {
        // the object was passed here
    });

}

注意:condition1condition2是互斥的。

以前,我做了这样的事情:

function create() {

    if (condition1) {
        // on ajax success
        callServiceCreate(object);
        return;
    }

    if (condition2) {
        // ajax call that doesn't make updates to object
    }

    callServiceCreate(object);

}

function callServiceCreate(object) {

    Service.create(object).success(function() {
        // the object was passed here
    });

}

这行得通,但我想知道这种情况是否适合 $q。

如果我用 $q 构造函数包装 condition1:

if (condition1) {
    return $q(function(resolve, reject) {
        // ajax success
        resolve(data);
    }
}

如何实现相同的功能,但只调用一次 callServiceCreate()/Service.create()

最佳答案

你显然可以在这里使用 $q.when 来传递 promise when 函数

代码

function create() {
    var condition1Promise;
    if (condition1) {
        condition1Promise = callServiceCreate(object);
    }

    if (condition2) {
        // ajax call that doesn't make updates to object
    }

    $q.when(condition1Promise).then(function(){
        Service.create(object).success(function() {
            // modify object here
            // the object was passed here
        });
    })
}

function callServiceCreate(object) {
    //returned promise from here to perform chain promise
    return Service.create(object).then(function(data) {
        // the object was passed here
        return data;
    });
}

关于javascript - 这种情况适合 $q 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31081689/

相关文章:

javascript - Angular JS + SharePoint 列表 + Rest API

angularjs - Angular 相当于 AngularJS $watch 是什么?

javascript - 如何将 Firebase 服务返回的对象作为数组打印(到控制台)

javascript - Jasmine 单元测试中仅模拟今天的日期

javascript - 如何从 ArrayBuffer 构建 Float32Array

Javascript:参数函数

JavaScript 错误消息 TypeError : undefined is not a function while using ngTagsInput

javascript - 允许非 ASCII 字符的(类似 twitter 的)主题标签的正则表达式

javascript - 有没有办法从cookie中获取数据?

javascript - 注册应用程序以访问 UBER API 时,Origin URI 应该是什么