Home > Web Front-end > JS Tutorial > body text

What is the use of buttons for $q asynchronous operations?

一个新手
Release: 2017-09-22 09:13:33
Original
1484 people have browsed it


'use strict';
angular.module('app').controller('positionCtrl',['$q','$http','$state','$scope','cache',function ($q,$http,$state,$scope,cache) {
    $scope.isLogin = false;    function getPosition() {
        var def = $q.defer();        $http.get('data/position.json',{ //1
            params:{
                id : $state.params.id
            }
        }).success(function(resp){
            $scope.position = resp;
            def.resolve(resp);
        }).error(function (err) {
           def.reject(err);
        });        return def.promise;//2
    }    function getCompany(id) {
        $http.get('data/company.json?id='+id).success(function(resp){
            $scope.company = resp;
        })
    };
    getPosition().then(function(obj){//4
        getCompany(obj.companyId);//5
    });    $q.all([fun1(),fun2()]).then(function (result) {})//6}]);/*
* $q是为了解决异步的问题
* 1、这里有个异步请求,我们在前面建一个$q.defer()函数来创建一个defer对象,延迟加载对象,
* 2、在异步请求下面返回def.promise属性,它也是一个对象,当我们处理完异步请求/操作的时候,我们就调用它的resolve()函数,把需要传入的参数传入进来,
* 当发送错误的时候,我在调用reject()函数,
* 3、这样当我们直接调用getPosition()函数的时候,得到的却是promise对象,
* 4、这个promise对象对象有一个then函数,这个then函数的作用就是当我们的异步请求调用resolve()之后,
* 5、它就会调用第一个传入的函数,同时把resolve()传入的参数传入进来。这样就可以把一个异步的操作变成一个同步的写法。
*
*
* 6、还有一种特殊的操作,就是我想当这两个操作同时执行完成之后再执行对应的操作,
* */
Copy after login

The above is the detailed content of What is the use of buttons for $q asynchronous operations?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!