反应es6一个接一个

时间:2017-05-25 15:01:52

标签: javascript ecmascript-6 fetch

我有以下React代码:

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

我怎么能这样做?

谢谢你的时间!

======编辑=======

在我的真实代码中,我尝试了:

private void sokaElevBetygActionPerformed(java.awt.event.ActionEvent evt) {                                              
     String elPP = tfAngivetId.getText();

     if (forms.Validering.textNotEmpty(tfAngivetId)){
         try {
             hogdb.fetchRows("select elev.FORNAMN, elev.EFTERNAMN, har_betyg_i.KURSBETYG FROM ELEV, HAR_BETYG_I WHERE ELEV.ELEV_ID = " + elPP);
             JOptionPane.showMessageDialog(rootPane, "data exist");
         }
         catch(InfException ex) {  
             System.out.println(ex.getMessage());
         }
    }
}

2 个答案:

答案 0 :(得分: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})
    })
}

答案 1 :(得分:0)

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

并致电this.fetchA()开始