Как я могу быстро создавать двести запросов API в API, то есть https://api.dictionaryapi.dev, в javascript? Я хочу поймать ошибки CORS со статусом ошибки 429 после использования fetch () , чтобы я мог повторить их или подождать дольше, если это необходимо, но я хочу бросить другие ошибки. Он постепенно ждет дольше, чтобы избежать этих 429 ошибок, но это слишком медленно. Кроме того, порядок выполнений не имеет значения.(async () => {
function wait(seconds) {
return new Promise(resolve => {
setTimeout(() => {
resolve()
}, seconds * 1000);
})
}
class FetchError extends Error {
constructor() {
super();
}
}
let i = 0;
let list = [];
const someWords = ["webisode", "gin rummy", "cruder", "decarburising", "corn-cob pipe", "viva voce", "jaunting-car", "station blacks", "fit into", "dry mounting", "misfile", "gain time", "name day", "encouraged", "spahi", "tricorns", "in seventh heaven", "clarkias", "co-equal", "jomon", "plant", "data set", "sutra", "hypnotised", "talkshows", "quilts", "mince-pie", "grassroot", "crossfit", "price relative", "green plover", "abeyance", "ferrocyanide", "anatomically", "manful", "dust devils", "squibbed", "kyu grades", "girning", "transgendered", "narcosis", "go hot and cold", "gambling dens", "cochleae", "rowing machine", "overloud", "poetize", "rattlesnake", "speeddating", "pastored", "harmonised", "be worth one's weight in gold", "non-employment", "clinch", "intelligibility", "frog orchid", "grantor", "asthenic", "bandhs", "cedilla", "subaudition", "bassinets", "inferential", "paper bank", "episternum", "gaba", "apocarpous", "carolinian", "cab sauvs", "constrain", "bell-hop", "sympto-thermal method", "dance cards", "mescaline", "cobalts", "paper-taffeta", "palmtop", "sagittal", "bazooms", "stew", "doronicums", "fish kettle", "national grids", "religo", "catchphrases", "multiprogramming", "re-taken", "called", "sheet feeder", "chirognomy", "albizzia", "straight-jacketing", "strike while the iron is hot", "odalisques", "scouser", "metabolite", "breaded", "palavers", "seceding", "hunks", "consequence", "brillo pad", "biweekly", "ultrafine", "compellingly", "inert gas", "suffragis", "dedendums", "stochastic", "overcharging", "high-and-mighty", "bordures", "farm-worker", "pesthouse", "world-beater", "meditates", "enacted", "ophthalmic optician", "bed-bugs", "molds", "geocode", "leave the door open", "retrodictions", "tiresome", "explicit", "gearlevers", "profoundly", "anti-semitism", "hemstitched", "a bit much", "bituminizing", "upbeats", "preppy", "outfalls", "schlemiels", "bench seats", "monologise", "commoditize", "disinhibited", "conservatism", "talked", "annuls", "disadvantageous", "wild men", "radiation patterns", "non-literary", "round dances", "transvaluing", "slokas", "streeties", "medical emergency", "side valve", "urophilia", "chain letter", "quick-freezes", "transliterated", "dobermann pinschers", "alkali metal", "out-vote", "cachinnated", "nurdle", "quinquenniums", "interfluve", "p45", "dazzles", "nonreturnable", "midship", "overturns", "mast", "hyperkalemia", "don't", "suntan lotions", "unsteadiest", "meissen", "apprehensive", "gastarbeiters", "squabbled", "deprecated", "soft-paste", "heaths", "cabin cruiser", "millies", "unicorns", "repeat fees", "gavels", "suck-holing", "saviour siblings", "interspacing", "paused", "catoptric", "coral snakes", "blood brother", "beast of prey", "nullities", "afterpains", "lgbtqia", "act of grace", "atory", "blocker", "pervasive"];
let success = 0;
const successIntervals = 20;
await someWords.reduce(async (array, item) => {
await array;
try {
if (success >= successIntervals) await wait((success / successIntervals) = 200 && data.status < 300) break;
throw new FetchError("Error " + data.status + ": Cannot fetch " + item);
}
const wordData = await data.json();
if (wordData === null || wordData?.title === "No Definitions Found") throw new FetchError("No definition found for " + item);
const completeWordData = {
word: item,
data: wordData
};
list.push(completeWordData);
i++;
success < successIntervals * 1.5 ? success++ : success = 0;
} catch (e) {
if (!(e instanceof FetchError || e instanceof TypeError)) throw e;
console.error(e);
}
})
})();
Подробнее здесь: https://stackoverflow.com/questions/796 ... handling-o
Асинхронно и быстро выполнять множество запросов API в JavaScript при обработке или предотвращении 429 сообщений об ошиб ⇐ Javascript
Форум по Javascript
1752384204
Anonymous
Как я могу быстро создавать двести запросов API в API, то есть https://api.dictionaryapi.dev, в javascript? Я хочу поймать ошибки CORS со статусом ошибки 429 после использования fetch () , чтобы я мог повторить их или подождать дольше, если это необходимо, но я хочу бросить другие ошибки. Он постепенно ждет дольше, чтобы избежать этих 429 ошибок, но это слишком медленно. Кроме того, порядок выполнений не имеет значения.(async () => {
function wait(seconds) {
return new Promise(resolve => {
setTimeout(() => {
resolve()
}, seconds * 1000);
})
}
class FetchError extends Error {
constructor() {
super();
}
}
let i = 0;
let list = [];
const someWords = ["webisode", "gin rummy", "cruder", "decarburising", "corn-cob pipe", "viva voce", "jaunting-car", "station blacks", "fit into", "dry mounting", "misfile", "gain time", "name day", "encouraged", "spahi", "tricorns", "in seventh heaven", "clarkias", "co-equal", "jomon", "plant", "data set", "sutra", "hypnotised", "talkshows", "quilts", "mince-pie", "grassroot", "crossfit", "price relative", "green plover", "abeyance", "ferrocyanide", "anatomically", "manful", "dust devils", "squibbed", "kyu grades", "girning", "transgendered", "narcosis", "go hot and cold", "gambling dens", "cochleae", "rowing machine", "overloud", "poetize", "rattlesnake", "speeddating", "pastored", "harmonised", "be worth one's weight in gold", "non-employment", "clinch", "intelligibility", "frog orchid", "grantor", "asthenic", "bandhs", "cedilla", "subaudition", "bassinets", "inferential", "paper bank", "episternum", "gaba", "apocarpous", "carolinian", "cab sauvs", "constrain", "bell-hop", "sympto-thermal method", "dance cards", "mescaline", "cobalts", "paper-taffeta", "palmtop", "sagittal", "bazooms", "stew", "doronicums", "fish kettle", "national grids", "religo", "catchphrases", "multiprogramming", "re-taken", "called", "sheet feeder", "chirognomy", "albizzia", "straight-jacketing", "strike while the iron is hot", "odalisques", "scouser", "metabolite", "breaded", "palavers", "seceding", "hunks", "consequence", "brillo pad", "biweekly", "ultrafine", "compellingly", "inert gas", "suffragis", "dedendums", "stochastic", "overcharging", "high-and-mighty", "bordures", "farm-worker", "pesthouse", "world-beater", "meditates", "enacted", "ophthalmic optician", "bed-bugs", "molds", "geocode", "leave the door open", "retrodictions", "tiresome", "explicit", "gearlevers", "profoundly", "anti-semitism", "hemstitched", "a bit much", "bituminizing", "upbeats", "preppy", "outfalls", "schlemiels", "bench seats", "monologise", "commoditize", "disinhibited", "conservatism", "talked", "annuls", "disadvantageous", "wild men", "radiation patterns", "non-literary", "round dances", "transvaluing", "slokas", "streeties", "medical emergency", "side valve", "urophilia", "chain letter", "quick-freezes", "transliterated", "dobermann pinschers", "alkali metal", "out-vote", "cachinnated", "nurdle", "quinquenniums", "interfluve", "p45", "dazzles", "nonreturnable", "midship", "overturns", "mast", "hyperkalemia", "don't", "suntan lotions", "unsteadiest", "meissen", "apprehensive", "gastarbeiters", "squabbled", "deprecated", "soft-paste", "heaths", "cabin cruiser", "millies", "unicorns", "repeat fees", "gavels", "suck-holing", "saviour siblings", "interspacing", "paused", "catoptric", "coral snakes", "blood brother", "beast of prey", "nullities", "afterpains", "lgbtqia", "act of grace", "atory", "blocker", "pervasive"];
let success = 0;
const successIntervals = 20;
await someWords.reduce(async (array, item) => {
await array;
try {
if (success >= successIntervals) await wait((success / successIntervals) = 200 && data.status < 300) break;
throw new FetchError("Error " + data.status + ": Cannot fetch " + item);
}
const wordData = await data.json();
if (wordData === null || wordData?.title === "No Definitions Found") throw new FetchError("No definition found for " + item);
const completeWordData = {
word: item,
data: wordData
};
list.push(completeWordData);
i++;
success < successIntervals * 1.5 ? success++ : success = 0;
} catch (e) {
if (!(e instanceof FetchError || e instanceof TypeError)) throw e;
console.error(e);
}
})
})();
Подробнее здесь: [url]https://stackoverflow.com/questions/79699722/asynchronously-and-quickly-make-many-api-requests-in-javascript-while-handling-o[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия