面试题继发执行 : 1s后执行10,等1s后输出20,再等1s后输出30
<script type="text/javascript">
function Pro(val) {
return new Promise((resolve, reject) => {
setTimeout(function() {
resolve(val)
}, 1000)
})
}
async function log(arrs) {
for(const item of arrs) {
var response = await Pro(item);
console.log(response);
}
}
log([10, 20, 30])
</script>
问题:给定一个 URL 数组,如何实现接口的继发和并发?
async 继发实现:
方法1
async function loadData() {
var res1 = await fetch(url1);
var res2 = await fetch(url2);
var res3 = await fetch(url3);
return"when all done";
}
方法2
async function loadData(urls) {
for (const url of urls) {
const response = await fetch(url);
console.log(await response.text());
}
}
async 并发实现:
方法1
async function loadData() {
var res = awaitPromise.all([fetch(url1), fetch(url2), fetch(url3)]);
return"whew all done";
}
方法2
async function loadData(urls) {
// 并发读取 url
const textPromises = urls.map(async url => {
const response = await fetch(url);
return response.text();
});
// 按次序输出
for (const textPromise of textPromises) {
console.log(await textPromise);
}
}