2017-05-25 84 views
-2

取一個我有以下陣營代碼:反應ES6一個

fetchA() { 
    fetch(aURL) 
    .then(response => response.json()) 
    .then(json => { 
     this.setState({ a: json}) 
    }) 
} 

fetchB() { 
    fetch(bURL) 
    .then(response => response.json()) 
    .then(json => { 
     this.setState({ b: json}) 
    }) 
} 

在網上大多數教程教你如如何wait until responses of both A and B been collected

Promise.all([fetchA, fetchB]) 
    .then(values => { 
    console.log(values[0]) 
    console.log(values[1]) 
    }) 

但我要的是fetch A, when A finished<results been colleted> then fetch B

我該怎麼做?

謝謝你的時間!

======編輯=======

在我真正的代碼,我嘗試:

fetchA(){ 
    fetch(aURL) 
    .then(fetchB()) 
    .then(response => console.log(response)) 
    .then(() => console.log('hi')) 
} 

fetchB(){ 
    fetch(bURL) 
    .then((response) => console.log(response)) 
} 

// call it 
this.fetchA() 

// output: 
// 
// A data 
// hi 
// B data 

// what I want is: 
// 
// B data 
// A data 
// hi 
+0

* 「但我要的是獲取A,當A完成<結果被colleted>然後取B中。」 *如果你跳過了'when'在該聲明中,您基本上具有您需要編寫的代碼的文本版本。方法和順序甚至非常接近。 **只是不要忘記從fetchA和fetchB返回。** –

回答

0

您可以使用then來鏈了。

fetch(aURL) 
    .then(response = > console.log('do something')) 
    .then(fetchB) 

更新:不要忘了來糾正fetchB。它應該返回Promise

fetchB() { 
    return fetch(bURL) 
    .then(response => response.json()) 
    .then(json => { 
     this.setState({ b: json}) 
    }) 
} 
+0

如果我擁有的只是fetchB和fetchA,那沒關係。但是如果我有fC呢?例如:'fetch(aURL).then(()=> console.log('a'))。then(fetchB())。then(fetchC())''不能保證'fetchB 'fetchC()',對吧? – mCY

+2

@mCY你爲什麼要加入'()'?如果你刪除它,你的評論的答案是,不,它會保證所述訂單。 –

+0

@Kevin B但我試着用'fetch(aURL).then(res => console.log(res))。然後(fetchB).then(()=> console.log('hi'))''。但'hi'出現在fetchB的輸出之前... – mCY

0
fetchA() { 
    fetch(aURL) 
    .then(response => response.json()) 
    .then(json => { 
     this.setState({ a: json}, this.fetchB); //this line changed 
    }) 
} 

,並呼籲this.fetchA()開始