0

I'm getting undefined on return value from the function

function checkAveStorage(path) {
    console.log("path " + path);
    disk.check(path, function(err, info) {
    if (err) {
        console.log(err);
        return -1;
    } else {
        console.log("info " + info.available);
        return ((info.available / info.total) * 100).toFixed(2); 
    }      
    });
}



app.get("/sysinfo", (req, res, next) => {   
     var storage = checkAveStorage('/mnt/usb');
     console.log(storage);
})

undefined value appear in console.

BoomRamada
  • 121
  • 1
  • 2
  • 11
  • 1
    Possible duplicate of [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – eol Jun 12 '19 at 10:22

2 Answers2

0

You are using callback so you must :

app.get("/sysinfo", (req, res, next) => {   
   checkAveStorage('/mnt/usb').then((storage)=>{
   console.log(storage)

})
Le Quang
  • 515
  • 4
  • 10
0

You are using callback which cannot return value, but you can use it inside that call back only. Other options are use promise or async/await.

function checkAveStorage (path) {
    console.log('path ' + path)
    return new Promise((resolve, reject) => {
        disk.check(path, function (err, info) {
            if (err) {
                console.log(err)
                reject(-1)
            } else {
                console.log('info ' + info.available)
                resolve(((info.available / info.total) * 100).toFixed(2))
            }
        })
    })
}

app.get('/sysinfo', (req, res, next) => {
    checkAveStorage('/mnt/usb').then((storage => {
        console.log(storage)
    }), (err) => {
        console.log(err)
    })
})

Another way with async/await

async function checkAveStorage(path) {
    try{
      const info = await disk.check(path);
      return ((info.available / info.total) * 100).toFixed(2);
    } catch(err){
      console.log(err);
      return -1;
    }
}



app.get("/sysinfo", async (req, res, next) => {   
     var storage = await checkAveStorage('/mnt/usb');
     console.log(storage);
})
mabc224
  • 722
  • 2
  • 10
  • 18