简体   繁体   English

多个 API 请求使用 Axios ReactJS

[英]Multiple API requests using Axios ReactJS

y'all... I am trying to make multiple requests to stockTweet API with an array of endpoints, I have used a for loop to fire the requests.你们大家...我正在尝试使用一组端点向 stockTweet API 发出多个请求,我使用了一个 for 循环来触发请求。 there should be a better way, searchTerm = [aapl, amzn.应该有更好的方法,searchTerm = [aapl, amzn. pypl] --- no restriction on number of terms. pypl] --- 对术语的数量没有限制。

https://api.stocktwits.com/api/2/streams/symbol/aapl.json https://api.stocktwits.com/api/2/streams/symbol/aapl.json

https://api.stocktwits.com/api/2/streams/symbol/amzn.json https://api.stocktwits.com/api/2/streams/symbol/amzn.json

https://api.stocktwits.com/api/2/streams/symbol/pypl.json https://api.stocktwits.com/api/2/streams/symbol/pypl.json

the number of requests is dynamic.请求的数量是动态的。

import React from 'react';
import axios from "axios";
import SearchBar from "./Searchbar";
import Card from "./Card";

const apiUrl = 'https://api.stocktwits.com/api/2/streams/symbol';
  const headers = {
    headers: {
      Accept: 'application/json',
    },
  };

class App extends React.Component{

  state = {};


    // --------------------------STATE--------------------------
    // {
    //     Apple.Inc: [
    //         {
    //             id: 111111,
    //             body: "aaaaaaaaaaa bbbbb ccccccc dddd",
    //             createdAt: timeStamp
    //         }
    //         {
    //             id: 222222,
    //             body: "aaaaaaaaaaa bbbbb ccccccc dddd",
    //             createdAt: timeStamp
    //         }
    //     ],
    //     Amazon.com: [
    //         {
    //             id: 333333,
    //             body: "aaaaaaaaaaa bbbbb ccccccc dddd",
    //             createdAt: timeStamp
    //         }
    //         {
    //             id: 444444,
    //             body: "aaaaaaaaaaa bbbbb ccccccc dddd",
    //             createdAt: timeStamp
    //         }
    //     ],
    // }


    onSearchSubmit = async (term) => {
      term = term.split(', ');
      for(let i = 0; i < term.length; i++){
        let symbol = term[i];
        const stocktwitsQuery = `${apiUrl}/${symbol}.json`;
        const resp = await axios.get(stocktwitsQuery, headers);
        let tweets = [];
        let allTweetsBody = res.data.messages.map((oneTweet) => tweets.push(oneTweet)); //add the tweet body to array
        this.setState({ ...this.state, [this.state[res.data.symbol['title']]]:  tweets });        
      }
    }


  render() {
    return( 
      <div className="ui container" style={{marginTop:'10px'}}>
          <SearchBar onSubmit={this.onSearchSubmit} />
      </div>
    );
  }

}

export default App;

How would I do that?我该怎么做? TIA TIA

PS Code is messed up..: :( PS代码搞砸了..: :(

This should work for n number of terms.这应该适用于 n 个术语。 Just split the terms into array and pass it as argument into promise.all只需将术语拆分为数组并将其作为参数传递给promise.all

const termUrls = terms.split(', ');
Promise.all(termsUrls).then((responses) => {
  console.log(response);
});

The downside of using promise.all in your case is that if one of your APIs is down so then your promise.all will reject all other ones.在您的情况下使用promise.all的缺点是,如果您的 API 之一出现故障,那么您的promise.all将拒绝所有其他 API。 In your case, you could use promise.allSettled()在你的情况下,你可以使用promise.allSettled()

The Promise.allSettled() method returns a promise that resolves after all of the given promises have either been fulfilled or rejected, with an array of objects that each describes the outcome of each promise. Promise.allSettled()方法返回一个 promise,它在所有给定的承诺都已实现或被拒绝后解析,其中包含一个对象数组,每个对象描述每个 promise 的结果。

It is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise.当您有多个不依赖于彼此的异步任务成功完成时,或者您总是想知道每个 promise 的结果时,通常会使用它。

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];

Promise.allSettled(promises).
  then((results) => results.forEach((result) =>  console.log(result.status)));

// expected output:
// "fulfilled"
// "rejected"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM