简体   繁体   English

如何从异步函数中获取数组的所有值

[英]How do I get all the values of an array from an async function

I would like to download an XML file, convert it to JSON, Fill an array, send Values to an different API.我想下载一个 XML 文件,将其转换为 JSON,填充一个数组,将值发送到不同的 API。

The things that work:有用的东西:

  • Download mulitple XML files下载多个 XML 文件
  • Convert it to JSON将其转换为 JSON
  • Fill an array with all the values用所有值填充数组

I can't get my head around the callback function.我无法理解回调函数。 The code below will output:下面的代码将输出:

Loading.. 34 done 34 done加载中.. 34 完成 34 完成

Expected is Loading..34 done预期正在加载..34 完成

function fillArray(callback) {
    console.log("Loading..");

    for (let i = 0;i < urlArray.length; i++){
        
        xml2json(urlArray[i], (json) => {
            
            let myArray = findProp(json, "value");
            
            for(let i = 0; i < myArray.length; i++){
                myArrlabel.push(myArray[i]);
               
            }
           
          callback();
        });
        
    }
    
    //return myArrlabel;
}

function useArray(){
    
    console.log(myArrlabel[15]);
    
    console.log("done");
    
}

fillArray(useArray);

The callback is inside the for loop, that's why I will get the above output.回调在 for 循环内,这就是为什么我会得到上面的输出。 It could be a stupid question but I can't understand how to code this correctly.这可能是一个愚蠢的问题,但我无法理解如何正确编码。

edit.. added xml2json()编辑 .. 添加了 xml2json()

function xml2json(url, callback){
    http.get(url, (resp) => {
      let data = '';

      // A chunk of data has been recieved.
      resp.on("data", (chunk) => {
        data += chunk;
      });

      // The whole response has been received. Print out the result.
      resp.on("end", () => {

          let json = parser.toJson(data, options);
          callback(json);
      });

    }).on("error", (err) => {
      console.log("Error: " + err.message);
    });
}

尝试添加一个 var ,每次数据加载时都会像您的回调一样加 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM