簡體   English   中英

如何鏈接多個單獨的JavaScript函數

[英]How to chain multiple separate JavaScript functions

我之前已經問過類似的問題,但沒有一個例子對我有意義。 (我找到的任何一個都沒有以我需要的清晰度為我解釋基礎知識。)

我有四個AngularJS函數。 每個調用REST服務並執行與任何其他函數無關的內容。 例如

$scope.step1 = function() { $http({  
    method: 'GET',  
    url: "http://www/end/point",  
    cache: true,
    headers: { "Accept": "application/jsonp;odata=verbose" }
}).success(function (data, status, headers, config) {
    $scope.step1data = data;
}).error(function (data, status, headers, config) {  
    $scope.logError(data);
});};

我想按順序調用這四個函數

  1. $ scope.step1
  2. $ scope.step2
  3. $ scope.step3
  4. $ scope.step4

並抓住遇到的任何錯誤。

我已將代碼縮小到下面,但它對我不起作用。 任何幫助將不勝感激。

$scope.step1().then(function() {
    $scope.step2();
}).then(function() {
    $scope.step3();
}).then(function() {
    $scope.step4();
}).catch(function(e) {
    console.log(e);
});

您需要將每個步驟函數的promise返回到then()回調,以便其生成的promise等待該promise:

$scope.step1().then(function() {
    return $scope.step2();
})...

首先,更改step1,step2,step3和step4以返回如下所示的承諾:

    $scope.step1 = function() {
    return $http({  
    method: 'GET',  
    url: "http://www/end/point",  
    cache: true,
    headers: { "Accept": "application/jsonp;odata=verbose" }
   })};

    $scope.step2 = function() {
    return $http({  
    method: 'GET',  
    url: "http://www/end/point",  
    cache: true,
    headers: { "Accept": "application/jsonp;odata=verbose" }
   })};

    $scope.step3 = function() {
    return $http({  
    method: 'GET',  
    url: "http://www/end/point",  
    cache: true,
    headers: { "Accept": "application/jsonp;odata=verbose" }
   })};

    $scope.step4 = function() {
    return $http({  
    method: 'GET',  
    url: "http://www/end/point",  
    cache: true,
    headers: { "Accept": "application/jsonp;odata=verbose" }
   })};

然后,像這樣將它們鏈接在一起:

$scope.step1().then(function (step1data) {
  $scope.step1data = step1data;
  $scope.step2().then(function (step2Data) {
    $scope.step2Data = step2Data;
       $scope.step3().then(function (step3Data) {
         $scope.step3Data = step3Data;
         $scope.step4().then(function (step4Data) {
            $scope.step4Data = step4Data;
         });
       });
  });
})

你需要使用promise,在你的控制器中,你應該注入$ q來處理promise。

 angularApp.controller('YourController', ['$q', '$scope',
    function ($q, $scope) {

        $scope.firstFunction = function () {
            var deferred = $q.defer();
            //Do things you want here...

            console.log(1);

            deferred.resolve();
            return deferred.promise;
        };

        $scope.secondFunction = function () {
            var deferred = $q.defer();
            //Do things you want here...

            console.log(2);

            deferred.resolve();
            return deferred.promise;
        };

        $scope.firstFunction().then(function () {
            $scope.secondFunction.then(function () {
                console.log(3)
            })
        })
    }]);

控制台登錄上面的功能將打印出來:

1
2
3

如果通過nsynjs同步執行代碼,則可以將異步函數與JavaScript提供的任何邏輯混合使用。 以下是您的代碼可能需要轉換的方式:

第1步:將異步函數包裝到通用的nsynjs-aware包裝器中:

// generic function to retrieve url
// ctx is a reference to caller pseudo-thread context
var httpUrl = function(ctx,url,$http) {
    var res={};
    $http({  
        method: 'GET',  
        url: url,  
        cache: true,
        headers: { "Accept": "application/jsonp;odata=verbose" }
    })
    .success(function (data, status, headers, config) {
        res.data = data;
        ctx.resume() // tells nsynjs to resume caller function
    }).error(function (data, status, headers, config) {
        ctx.resume(data) // resume caller function with exception
        // or replace with these 2 lines if you don't want exception
        // res.error = data;
        // ctx.resume()
    });
    return res;
};
getUrl.nsynjsHasCallback = true; // this tells nsynjs engine that it
                                // should pause execution and wait until ctx.resume() is called from callback

步驟2.將您的邏輯編寫為同步,並將其置於函數中:

function synchronousCode(param1, param2) {
    var step1 = function() {
        var data = httpUrl(nsynjsCtx,"nsynjs/examples/data/file1.json").data;
        console.log("data is ready at this point:",data);
        // do staff this data
        return data;
    };
    var step2 = function() {
        var data = httpUrl(nsynjsCtx,"nsynjs/examples/data/file2.json").data;
        console.log("data is ready at this point:",data);
        // do staff this data
        return data;
    };

    console.log( step1(param1) + step2(param2) ); // do more staff with data
}

步驟3.通過nsynjs運行同步代碼:

nsynjs.run(synchronousCode,{},"value for param1","value for param1",function(){
    console.log("Synchronous Code done");
})

更多示例: https//github.com/amaksr/nsynjs/tree/master/examples

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM