我正在尝试在 React 应用程序中使用 YouTube Data API v3 在 YouTube 上创建播放列表。但是,我遇到 429 错误,表明我的资源已耗尽。为了解决这个问题,我实施了具有随机延迟的指数退避策略,但我仍然达到了速率限制。这是我当前的实现:
我的代码
``import axios from "axios";
// Helper function to generate a random delay within a range
const getRandomDelay = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
const exponentialBackoff = async (fn, retries = 3, delay = 1000) => {
try {
return await fn();
} catch (error) {
if (
retries > 0 &&
error.response &&
(error.response.status === 403 || error.response.status === 429)
) {
const randomDelay = getRandomDelay(delay, delay * 2);
await new Promise((resolve) => setTimeout(resolve, randomDelay));
return exponentialBackoff(fn, retries - 1, delay * 2);
} else {
throw error;
}
}
};
export const createYouTubePlaylist =
(playlistName) => async (dispatch, getState) => {
const { youtubeAccessToken } = getState().auth;
const createPlaylist = async () => {
try {
const response = await axios.post(
"https://www.googleapis.com/youtube/v3/playlists",
{
snippet: {
title: playlistName, // Remove quotes around playlistName
description: "Playlist created from Spotify",
},
status: {
privacyStatus: "public",
},
},
{
headers: {
Authorization: `Bearer ${youtubeAccessToken}`,
Accept: "application/json",
},
params: {
part: "snippet,status",
},
}
);
console.log("Created Playlist:", response.data);
return response.data;
} catch (error) {
console.error("Error creating YouTube playlist:", error);
throw error; // Rethrow the error to handle it outside
}
};
return exponentialBackoff(createPlaylist)
.then((data) => {
console.log("Playlist created successfully:", data);
return data;
})
.catch((error) => {
console.error("Error creating YouTube playlist:", error);
return null; // Return null or handle the error as needed
});
};`
`
错误:429 资源已耗尽
你能解决这个问题吗?我也遇到同样的问题