【发布时间】:2020-08-17 22:11:44
【问题描述】:
大家好
在设定承诺和玩弄结果时遇到问题。
我定义了 2 个 URL 数组,目标是通过仅保留存在的文件来过滤文件(使用 fetch),然后在完成后触发一个显示结果的函数。
我想使用 Promise 方法和 fetch() 函数。
我为每个数组创建了 1 个仅过滤现有文件的承诺。在触发另一个函数之前,我需要等待 2 个 Promise 完成。
我查看了互联网并尝试了多种方法,但无法使其按预期工作。它显示了结果,但我不能玩它们,所以我可能做错了。
很高兴得到一些帮助!
见下面我的代码:
const Primary = [
'https://jsonplaceholder.typicode.com/posts', //file exists
'/data/file01', //file dont exist
'https://jsonplaceholder.typicode.com/users', //file exists
'/data/file02' //file dont exist
];
const Diverse = [
'/data/file0.txt', //file dont exist
'https://jsonplaceholder.typicode.com/albums', //file exists
'/data/file5.txt' //file dont exist
];
const P1 = new Promise(function(resolve, reject) {
Primary.forEach(function (elem, index) {
fetch( elem )
.then(function(response) {
if (response.status != 404) {
arr1.push (response.url);
return (response.url);
}
})
.catch(function(error) {
console.log("Error ", error);
});
if (index==(Primary.length-1))
resolve (arr1);
});
});
const P2 = new Promise(function(resolve, reject) {
Diverse.forEach(function (elem, index) {
fetch( elem )
.then(function(response) {
if (response.status != 404) {
arr2.push (response.url);
return (response.url);
}
})
.catch(function(error) {
console.log("Error ", error);
});
if (index==(Diverse.length-1))
resolve (arr2);
});
});
// Promise.all waits until all jobs are resolved
Promise.all( [P1, P2] )
.then(function (responses) {
console.log ('Responses:', responses);
responses.forEach(function (element, index) {
console.log (element);
element.forEach(function (el, id) {
console.log (el);
});
});
console.log('Test sync');
});
再次感谢 亚历克斯
【问题讨论】:
标签: javascript promise async-await fetch