【发布时间】:2018-09-29 01:59:35
【问题描述】:
我正在尝试编写一个函数(使用 fetch API)来同时下载一些文件,但在下载所有文件之前返回。就是想不通。
这是我尝试过的。
files = ["file1.xml", "file2.xml", "file3.xml"];
let res = get_files(files);
//TypeError: res[0] is undefined
console.log("res: " + res[0].getElementsByTagName("NAME")[0].childNodes[0].nodeValue);
function get_files(files){
let ret_files = [];
files.map(file => { //Create a new anonymous array full of promises (one per fetch).
fetch(file); //Triger the download
}).map(async prom => { //Another array with promises.
return await prom; //Waits for ALL the files to download.
}).forEach(p => {
p.then(a => ret_files.push(a)); //Populate 'ret_files' array.
//This works:
console.log("Inside function: " + ret_files[0].getElementsByTagName("NAME")[0].childNodes[0].nodeValue);
});
return ret_files;
}
据我所知,函数get_files() 在调用时会立即返回。我怎样才能等到ret_files 数组完全填充?
【问题讨论】:
标签: javascript asynchronous fetch