2017-10-25 5 views
-1

私はこの種のJavaScriptプログラミングでは初心者ですが、私の質問のいくつかはあなたのために愚かに見えるかもしれません。プロミス/ A +と、非同期性がJavascriptでどのように動作するか

最近、私はSpring Boot and Reactに関するチュートリアルを読んで実装していました。このチュートリアルでは、作者はrest(package.json - "rest": "^ 1.3.1")というライブラリを使用していましたが、それはPromies/A+というライブラリに基づいています。

私はチュートリアルを実装しようとしましたが、チュートリアルよりもツリー構造で他のタイプのデータ構造を持っていますので、1つのRestコールを作成し、最初のコールの解決策を作成する必要があります。 、私は私が説明することができない振る舞いを持って、コールは次のように見える(擬似コード)。

client({method: 'GET', path: 'http://localhost:8080/service1'}) 
    .then(response =>{ 
     this.setState({result1 : response.entity._embedded.systems}) 
     return this.state.systems; 
    }) 
    .then(function(results1) { 
     { 
      results1 && results1.map(
       function(result) { 
        client({method: 'GET', path: result._links.services.href }) 
        .done(response => { 
         var results2 = response.entity._embedded.services 
         result.services = results2; 
        }); 
       } 
      ) 
     } 
    } 
    ); 

今私の問題は、この2、その後(..)ブロックは、完全に非同期に実行実際に私が反応使用していると私は反応する(....)this.setStateを呼び出した瞬間は、結果だけながら、コンポーネントを描画します最初の呼び出しから、このコードを 'componentDidMount()'に設定していますが、 'componentDidMount()'の実行が終了したときにのみ 'render()'が開始されることを期待しています。

私は最初の 'then(...)'ブロックで2番目のRest Service呼び出しを試みましたが、何も変更されませんでした。

client({method: 'GET', path: 'http://localhost:8080/service1'}) 
    .then(response =>{ 
     var tmp = response.entity._embedded.systems; 
     tmp && tmp.map(
      function(result) { 
       client({method: 'GET', path: result._links.services.href }) 
       .done(response => { 
        var results2 = response.entity._embedded.services 
        result.services = results2; 
        }); 
       } 
     this.setState({result1 : response.entity._embedded.systems}) 
    }) 

同じ動作で、最初のRest Callからの結果ですが、2番目のものはありません。終わり

、私は次のように作られたこの作品を作るために、

setTimeout(
    function() { 
     this.setState({result1: tmp}); 
    } 
) 

が、これはこれを行うための正しい方法にすることはできません。

私の質問は、私は間違って何をしているのですか?

答えのための....

答えて

0

これはちょっと役立ちます。 あなたがpromise.allに約束の配列を渡すことができます。私は、[編集]

client({method: 'GET', path: 'http://localhost:8080/service1'}) 
.then(response =>{ 
    this.setState({result1 : response.entity._embedded.systems}) 
    return this.state.systems; 
}) 
.then(function(results1) { 
     var promises = results1.map(
      function(result) { // return the created promise 
       return client({method: 'GET', path: result._links.services.href }) 
       .done(response => { 
        var results2 = response.entity._embedded.services 
        result.services = results2; 
       }); 
      } 
     ) 
     return Promise.all(promises) // return promiseCollection 
    } 
}); 

私の変更をコメントしました。それはすべての約束が満たされるまで待ってから、そのthen()メソッドを呼び出します。

+0

最初に、答えのためのthxが、私はこれで達成するものを私に説明することができます:)? 「Promise.all(約束)」は同期ポイントなのでしょうか? – posthumecaver

関連する問題