为了账号安全,请及时绑定邮箱和手机立即绑定

如何调用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 关注
  • 202 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信