猿问

如何调用rest api并将结果提供给后续的promise调用

我有以下代码调用一个休息 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});

        });

    }


郎朗坤
浏览 203回答 3
3回答

UYOU

这个怎么样async myMethod() {&nbsp; var self = this;&nbsp; var myArray = [];&nbsp; var result = await getCustomers();&nbsp; for(var index = 0; index < result.length; index++) {&nbsp; &nbsp;var booking = await this.getBookings(result[index].customerId);&nbsp; &nbsp;myArray.push(<div className="col">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{result[index].customerId}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{booking}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div>&nbsp; }&nbsp;self.setState({customers: myArray});}&nbsp;&nbsp;

偶然的你

正如您所做的那样getCustomers(),您必须获得 with 的承诺结果then。所以你的代码看起来像这样:myMethod() {&nbsp; &nbsp; var self = this;&nbsp; &nbsp; var myArray = [];&nbsp; &nbsp; getCustomers().then(result => {&nbsp; &nbsp; &nbsp; &nbsp; for(var index = 0; index < result.length; index++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.getBookings(result[index].customerId).then(bookings => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; myArray.push(<div className="col">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{result[index].customerId}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{bookings}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div>);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; self.setState({customers: myArray});&nbsp; &nbsp; });&nbsp;}请注意,此解决方案假定您没有使用 ES6async/await结构。否则其他答案更好。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答