AngularJS:$ http和$ q承诺的工作方式不同

时间:2016-11-23 11:04:22

标签: javascript angularjs promise

我的服务中有getUsers个功能:

function getUsers() {
    return $q( (resolve, reject) => {
        $timeout(() => {
            let flag = true;

            flag ? resolve(users) : reject("Error Users");

        }, 2000);
    });
}

getExampleResponse()基于$http服务

    function getExampleResponse() {
        return $http
            .get("./example.json");
    }

我知道$http.get应该回报承诺。在我的控制器中,我有以下代码:

    let userPromise = myService.getUsers(),
        examplePromise = myService.getExampleResponse();

    $q.all([userPromise, examplePromise])
        .then(getAllDataSuccess)
        .catch(getTasksError)
        .finally(getTasksComplete);

    function getAllDataSuccess(dataArray) {
        console.log(dataArray[0]); // I have user object here
        console.log(dataArray[1]); // I have promise object here
    } 

所以在then回调后,在一个案例中我有所需的对象,在其他情况下,我继续承诺。怎么了?

1 个答案:

答案 0 :(得分:-1)

getUsers()你要返回$ q。如果你想传递承诺然后返回

function getUsers() {
    var d = $q.defer();
    // Your code
    return d.promise;
}