来自两个API的搜索结果

问题描述 投票:0回答:1

我想从我的搜索页面上的两个API获取数据。我可以使用Promise.all()吗?以及如何做?

// npm i react-filter-search

   const SearchPage = (props) => {
            useEffect(() => {
                fetch(' https://heka4.apache.techcollege.dk/api/ingredients/')
                      .then(response => response.json())
                      .then((data) => {setData(data)
                        setSearchWord(props.match.params.searchWord)
                    setLoader('done')});
            }, []);
reactjs search react-hooks use-effect
1个回答
1
投票

使用Promise.all基本上就像每个诺言本身一样,但是按提供的诺言顺序返回结果数组。看起来像这样:

const source1 = fetch('https://heka4.apache.techcollege.dk/api/ingredients/');
const source2 = fetch('...');
Promise.all([source1, source2])
.then((allResponses) => allResponses.map(singleResponse => singleResponse.json()))
.then(([result1, result2]) => {
  // Do what you want with the two responses.
});

如果您希望得到的结果是使用两者中较快的一个,例如对于某种形式的负载平衡,还有Promise.race仅与第一个响应一起前进。

另一种选择是使用Promise.allSettled,尤其是在不确定所有请求是否成功时。与Promise.all的不同之处在于,它将结果包装在描述响应状态的对象中,如下所示:{ status: "fulfilled", value: '<result>' }{ status: "rejected", value: '<result>' }

© www.soinside.com 2019 - 2024. All rights reserved.