如何在每个请求仅支持一个ID的API端点中获取多个ID



我使用Coingecko API获取价格数据和时间(Unix(,以图表形式输出,但我使用的端点只支持每个请求一个ID。

document.onreadystatechange = async () => {
if (document.readyState === "complete") {
const coin = "bitcoin";
const currency = "brl";


const response = await fetch(
`https://api.coingecko.com/api/v3/coins/${coin}/market_chart?vs_currency=${currency}&days=10&interval=hourly
`
);
const data = await response.json();

const prices = data.prices.map((e) => e[1]);
const date = data.prices.map(i => i[0]);

我需要这个函数也对solana、cardano、ripple、dash和litecoin 做同样的操作

如果您的API每个请求只支持一个ID,并且您需要多个ID,那么您将需要发出多个请求。

一种并行完成并等待所有操作完成后再继续的方法是

const data = await Promise.all([
fetch(endpoint1).then(response => response.json()), 
fetch(endpoint2).then(response => response.json()), 
fetch(endpoint3).then(response => response.json())
]);

以上操作将导致data包含每个端点的响应数组——data[0]将是来自endpoint1的json,来自endpoint2的data[1],依此类推。你需要通过它们来获得每个ID的价格和日期(显然,Promise.al((尝试将所有响应合并为一个是没有意义的,因为你无法知道哪个ID对应哪个价格(

最新更新