2017-06-23 4 views
1

私はAngularJSの初心者ですし、約束APIに苦労しています。私が得るために私のコントローラでsave()機能を実装しました:関数が複数のリソースコールを終了するのを待ちます。

  1. 規制バージョンが保存される規制のバージョンは
  2. を保存し、そのインストール・タイプのすべてが非同期並列方法
  3. に保存されます

  4. saved!ログには、すべてが終わった後、私は現在、私のコントローラを持っているコードです

(私の実際のアプリケーションでは、私はここに他のアプリケーションの状態に行きたい)を表示しました3210

var saveRegulationInstallationTypes = function (result) { 
    var saveOperations = []; 
    angular.forEach(vm.installationTypeRegs, function (
      installationTypeReg, key) { 
     installationTypeReg.regulationVersion = result; 
     var res = InstallationTypeReg.update(installationTypeReg, function() { 
       console.log('Installation type updated'); 
      }); 
     saveOperations.push(res); 
    }); 
    return $q.all(saveOperations); 
} 

function save() { 
    var regulationVersionSaved = RegulationVersion.update(vm.regulationVersion); 
    return regulationVersionSaved.$promise.then(
     function (result) { 
      saveRegulationInstallationTypes(result).then(console.log('saved!')); 
    }); 
} 

RegulationVersionInstallationTypeRegは実体上のHTTP操作のそれぞれについて、$resource方法を返すサービスです。 save()メソッドを実行するときの問題は、Installation type updatedより前にsaved!ログを取得することです。私は、私の関数からq.allを返すので、コールバックを呼び出す前にすべての内部操作を終了するのを待つべきだと思います。

私は間違っていますか?

答えて

1

2つの問題があります:1) "saveOperations.push(res);" - "saveOperations.push(res。$ promise);"にする必要があります。 - 配列のように、オブジェクト全体ではなく約束を格納する必要があります。 2)saveRegulationInstallationTypes(result).then(console.log( 'saved!')); saveRegulationInstallationTypes(result).then(function(){console.log( 'saved!')});そうでなければなりません。

+0

私は約束を保存するためにそれを変更しても、ロギングの順序は同じままです。 –

+0

以下の変更を試してください: "saveRegulationInstallationTypes(result).then(console.log( 'saved!'));" 〜 "saveRegulationInstallationTypes(result).then(function(){console.log( 'saved!')});" –

+0

ええ、これはあなたの答えでトリックを作る。このコメントを編集して回答に追加してください。ありがとう! –

関連する問題