Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

封装一个并发函数 #174

Open
wuweijia opened this issue Aug 26, 2024 · 0 comments
Open

封装一个并发函数 #174

wuweijia opened this issue Aug 26, 2024 · 0 comments

Comments

@wuweijia
Copy link
Owner

// 并发请求
const urls = []
for (let i = 1; i <= 20; i++) {
	urls.push(`https://jsonplaceholder.typicode.com/todos/${i}`)
}

const fetchMultiple = (urls, max, callback) => {
	const len = urls.length
	const result = []
	let requestIndex = 0

	const request = (index) => {
		requestIndex++
		const url = urls[index];
		fetch(url).then(res => res.json()).then(data => {
			console.log(`请求 ${url} 完成`, data);
			// 保存结果 要与 url 的位置对应
			result[index] = data
		}).catch(err => {
			console.error(`请求 ${url} 失败`, err);
		}).finally(() => {
			// 判断是否所有请求都完成
			if (result.length === len) {
				callback(result)
			} else if (requestIndex < len) {
				request(requestIndex)
			}
		})
	}

	for (let index = 0; index < max; index++) {
		request(index)
	}
}

fetchMultiple(urls, 5, (result) => {
	console.log('所有请求完成', result);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant