Ad
Unable To Return Value From Function
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
Related Questions
- → Maximum call stack exceeded when instantiating class inside of a module
- → Browserify api: how to pass advanced option to script
- → Node.js Passing object from server.js to external modules?
- → gulp-rename makes copies, but does not replace
- → requiring RX.js in node.js
- → Remove an ObjectId from an array of objectId
- → Can not connect to Redis
- → React: How to publish page on server using React-starter-kit
- → Express - better pattern for passing data between middleware functions
- → Can't get plotly + node.js to stream data coming through POST requests
- → IsGenerator implementation
- → Async/Await not waiting
- → (Socket.io on nodejs) Updating div with mysql data stops without showing error
Ad