0

How can I get a return value from the following code? I don't want to just console log it

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;
    });
  }

running this will return undefined while running a console log just before return percent will give me the correct answer..

  • 1
    Since it’s async the return statement will go to the next `then()` statement, which you don’t have. Instead of returning you could call a function that has the rest of your code that handles the result. – Kokodoko Apr 06 '19 at 14:59

1 Answers1

1

You can simply add a then-handler to process the resolved value, e.g:

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;
    });
}

In order to access the result outside the get_disk_space function scope, you need to do:

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

In case the function where you call get_disk_space is async, you can simply do:

async function testFunc() {
const result = await get_disk_space();
// handle result
}
eol
  • 23,236
  • 5
  • 46
  • 64