How to use fetch within a for-loop, wait for results and then console.log it(如何在 for 循环中使用 fetch,等待结果,然后 console.log 它)
问题描述
我有这个问题:我想在一个 for 循环中进行多次 fetch 调用.调用次数取决于用户输入(在我的示例中,我有三个).我怎样才能让它遍历所有的 fetch 请求,然后 console.log 关闭电话号码?
i have this problem: i want to make multiple fetch calls within a for-loop. The number of calls depend on the user input (in my example i have three). How can i make it loop through all the fetch requests and then console.log the number off calls?
函数 getPosts(){
function getPosts(){
let url = ["https://www.freecodecamp.org", "https://www.test.de/, http://www.test2.com"];
let array = new Array;
for (let i = 0; i < url.length; i++) {
console.log(url[i]);
fetch(url[i])
.then(res => {return res.text(); })
.then(res => {
let reg = /<meta name="description" content="(.+?)"/;
res = res.match(reg);
array.push(res);
console.log(res);
}
)
.catch(status, err => {return console.log(status, err);})
}
console.log (array.length);
}
它 console.logs 是 0 而不是 3,因为它不会等待所有的 Promise 都被解决.我怎样才能使它成为console.log 3?如果您知道解决方案,请帮助我.
It console.logs 0 instead of 3, cause it doesn't wait for all the promises to be resolved. How can i make it to console.log 3? If you know a solution, please help me out.
推荐答案
你不能调用console.log(array.length),直到之后所有的promise都完成了.那么为什么不这样呢?
You can't call console.log(array.length) until after the promises are all done. So why not something like this?
let url = ["https://www.freecodecamp.org", "https://www.test.de/, http://www.test2.com"];
let array = new Array;
var fetches = [];
for (let i = 0; i < url.length; i++) {
console.log(url[i]);
fetches.push(
fetch(url[i])
.then(res => {return res.text(); })
.then(res => {
let reg = /<meta name="description" content="(.+?)"/;
res = res.match(reg);
array.push(res);
console.log(res);
}
)
.catch(status, err => {return console.log(status, err);})
);
}
Promise.all(fetches).then(function() {
console.log (array.length);
});
}
Promise.all 等待所有提取完成,然后它会打印 #.
Promise.all waits for all the fetches to finish, THEN it'll print the #.
这篇关于如何在 for 循环中使用 fetch,等待结果,然后 console.log 它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 for 循环中使用 fetch,等待结果,然后 console.log 它
基础教程推荐
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
