Return 来自异步函数的数据

Return data from async function

我已经阅读了很多关于回调的内容,但还是不明白...

我正在执行一个异步函数,该函数将一个包含可用磁盘信息的字符串添加到数组中 space。

所有这些代码都在一个脚本中,我希望能够在其他人中使用该数组。到目前为止,我尝试 return 它并将其作为参数传递...但它在完成任务之前执行。

var diskspace = require('diskspace');
var fs = require('fs');
var aux;

function getDiskSpace(json){
    diskspace.check('C',function(err, total, free, status){ 
        aux=new Object();
        aux.name="diskspace";
        aux.value=(((total-free)/(1024^3)).toFixed(2)+"MB used, "+(free*100/total).toFixed(2)+"% free");
        json.push(aux);
    }); 
    aux= new Object();
    aux.name="date";
    aux.value=(new Date().toLocaleString());
    json.push(aux);
    aux= new Object();
    aux.name="arduinos";
    aux.value=JSON.parse(fs.readFileSync("./data/dirs.json","utf8"));
    json.push(aux); 
}

module.exports=getDiskSpace;

进入主程序后,我发送它 JSON:

    var array=new Array();
    var getDiskSpace=require('./getIndexInfo.js');
    getDiskSpace(array);
    res.writeHead(200,{"Content-Type": "application/json"});
    res.end(JSON.stringify(array));

你能告诉我正确的方法吗? 我知道这已经被讨论了很多,但我也一直在阅读关于 promises 的内容,而且我阅读的越多,我就越困惑,抱歉。

对于任何异步函数,您都需要有一个回调函数,该函数会在操作完成后执行。您可以像这样修改您的代码并尝试。

var diskspace = require('diskspace');
var fs = require('fs');
var aux;

function getDiskSpace(cb){
    diskspace.check('C',function(err, total, free, status){ 
      var arr = [];
      var aux=new Object();
      aux.name="diskspace";
      aux.value=(((total-free)/(1024^3)).toFixed(2)+"MB used, "+(free*100/total).toFixed(2)+"% free");
      arr.push(aux);

      aux= new Object();
      aux.name="date";
      aux.value=(new Date().toLocaleString());
      arr.push(aux);

      aux= new Object();
      aux.name="arduinos";
      aux.value=JSON.parse(fs.readFileSync("./data/dirs.json","utf8"));
      arr.push(aux); 

      //Pass the array to the callback
      //In case of any error pass the error info in the first param
      cb(null, arr);
    });
}

module.exports=getDiskSpace;

用法

var getDiskSpace=require('./getIndexInfo.js');
getDiskSpace(function (err, arr) {
  ///If err is not null then send error response
  res.writeHead(200,{"Content-Type": "application/json"});
  res.end(JSON.stringify(arr));
});