JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
JavaScript
/**
* @param {(() => Promise<T>)[]} promises
* @returns {Promise<T[]>}
* @template T
*/
const sequential = async (promises) => {
const first = promises.shift()
if (first == null) {
return []
}
const results = []
await promises
// 末尾に空のPromiseがないと、最後のPromiseの結果をresultsにpushできないため
.concat(() => Promise.resolve())
.reduce(async (prev, next) => {
const res = await prev
results.push(res)
return next()
}, Promise.resolve(first()))
return results
}
// 使う側
const main = async () => {
const promises = [
() => axios.get("https://api.github.com/search/users?q=siro"),
() => axios.get("https://api.github.com/search/users?q=yamato"),
() => axios.get("https://api.github.com/search/users?q=kiso"),
]
const results = await sequential(promises)
console.log(results)
}
main()