无法从函数返回值

时间:2019-06-12 10:06:19

标签: node.js

我在从函数返回值时变得不确定

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

未定义的值出现在控制台中。

2 个答案:

答案 0 :(得分:0)

您正在使用callback,因此必须:

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

})

答案 1 :(得分:0)

您正在使用无法返回值的回调,但只能在该回调内使用它。其他选项是使用promise或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)
    })
})

使用异步/等待的另一种方式

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