Created
August 17, 2020 15:58
-
-
Save chrisryana/3a3af49ebc3f6d5f4a38a1bb24fb6406 to your computer and use it in GitHub Desktop.
Реализация запросов на сервер внутри цикла
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getData = async (pagesCount, params) => { | |
const pagesData = []; | |
const promises = []; | |
const { limit } = params; | |
for (let i = 1; i <= pagesCount; i++) { | |
const promise = api.method({ | |
params: { ...params, offset: (i - 1) * limit }, | |
}); | |
// сначала собираем промисы в одном массиве, не дожидаемся ответа | |
promises.push(promise); | |
} | |
// await чтобы дождаться результата в месте, где вызывается функция | |
await Promise.all(promises) | |
.then(res => { | |
res.forEach(({ data }) => { | |
pagesData.push(...data); | |
}); | |
}) | |
.catch(e => { | |
console.error(e.message); | |
}); | |
return pagesData; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment