Ad

Unable To Return Value From Function

- 1 answer

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.

Ad

Answer

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);
})
Ad
source: stackoverflow.com
Ad