【问题标题】:How to wait for an async function?如何等待异步函数?
【发布时间】: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


【解决方案1】:

您的代码中存在一些问题:

 files.map(file => {
   fetch(file); // triggers the download, but you dont do anything, not even return it
  }).map(async prom => // prom is undefined?
    return await prom; //Waits for undefined ?! And thats basically a noop
  }).forEach(p => { // p is undefined again
    p.then(a => ret_files.push(a)); // Why?!     
 });

 return ret_files; // you return *now* and dont wait for anything?!

这是它应该如何工作的:

 function getFiles(files){
   return Promise.all(files.map(file => fetch(file)));
 }

这只是创建了一个 fetch Promise 数组,并等待所有这些。

你可以像这样使用它:

 (async function() {

   let res = await getFiles(files);
   console.log(res[0]);
 })()

【讨论】:

  • 感谢您的出色回答,但我想返回文件的内容,而不是 Promise。获得文件内容后如何处理承诺并返回??
  • @algolejos 这正是上面的代码所做的。它返回一个解析为文件内容数组的承诺。
猜你喜欢
  • 2023-03-13
  • 1970-01-01
  • 2017-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-30
  • 1970-01-01
相关资源
最近更新 更多