从异步表达式中获取返回值

时间:2019-04-06 14:45:08

标签: javascript node.js

如何从以下代码中获取返回值?我不想只是控制台登录

function get_disk_space(callback){
    checkDiskSpace('C:\\').then((diskSpace) => {
      var free = Math.floor(diskSpace.free/1000000000)
      var size = Math.floor(diskSpace.size/1000000000)
      var used = size - free
      percent = (size - free)
      percent = percent/size*100
      percent = Math.floor(percent)+'%'
      return percent;
    });
  }

运行此命令将在运行控制台日志时返回未定义的结果,而返回百分比将给我正确的答案。

1 个答案:

答案 0 :(得分:1)

您可以简单地添加一个then处理程序来处理解析的值,例如:

function get_disk_space(callback) {
    return checkDiskSpace('C:\\').then((diskSpace) => {
        var free = Math.floor(diskSpace.free / 1000000000)
        var size = Math.floor(diskSpace.size / 1000000000)
        var used = size - free
        percent = (size - free)
        percent = percent / size * 100
        percent = Math.floor(percent) + '%'
        return percent;
    });
}

为了访问get_disk_space函数范围之外的结果,您需要执行以下操作:

get_disk_space().then((result) => {
   //log and handle your result
   console.log(result);
   // handle your result
});

如果您调用get_disk_space的函数是异步的,则只需执行以下操作:

async function testFunc() {
const result = await get_disk_space();
// handle result
}