亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何調用rest api并將結果提供給后續的promise調用

如何調用rest api并將結果提供給后續的promise調用

郎朗坤 2021-08-26 16:05:56
我有以下代碼調用一個休息 api,然后使用結果數據并將值提供給后續的 api 調用。不知道如何使這項工作..!您可以在第二種方法中看到我的評論,這會顯示數據,但是因為這是一個承諾,所以我不確定如何將其傳回?有任何想法嗎?謝謝代碼片段componentDidMount() {  myMethod();}getBookings(id) {    getCustomerBookings(id).then(res => {        console.log(res);  // displays the data correctly        return res;    });}    myMethod() {    var self = this;    var myArray = [];    getCustomers().then(result => {        for(var index = 0; index < result.length; index++) {            myArray.push(<div className="col">                     {result[index].customerId}  // displays customer id as expected                     {this.getBookings(result[index].customerId)} // attempt                 </div>            self.setState({customers: myArray});        });    }
查看完整描述

3 回答

?
UYOU

TA貢獻1878條經驗 獲得超4個贊

這個怎么樣


async myMethod() {

  var self = this;

  var myArray = [];

  var result = await getCustomers();

  for(var index = 0; index < result.length; index++) {

   var booking = await this.getBookings(result[index].customerId);

   myArray.push(<div className="col">

                     {result[index].customerId} 

                     {booking}

                 </div>


  }

 self.setState({customers: myArray});

}  


查看完整回答
反對 回復 2021-08-26
?
偶然的你

TA貢獻1841條經驗 獲得超3個贊

正如您所做的那樣getCustomers(),您必須獲得 with 的承諾結果then。所以你的代碼看起來像這樣:


myMethod() {

    var self = this;

    var myArray = [];

    getCustomers().then(result => {

        for(var index = 0; index < result.length; index++) {

          this.getBookings(result[index].customerId).then(bookings => {

            myArray.push(<div className="col">

                     {result[index].customerId}

                     {bookings}

                 </div>);

          });

        }

    self.setState({customers: myArray});

    }); 

}

請注意,此解決方案假定您沒有使用 ES6async/await結構。否則其他答案更好。


查看完整回答
反對 回復 2021-08-26
  • 3 回答
  • 0 關注
  • 221 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號