0

Node.js newbie here. I'm writing a monitoring node in node-red and wanted to use the "node-df" package to get some data of disk usage. I'm using the function call as the code below and wanted to store the response in a variable outside the function scope. However, the response does not get stored in the df_str variable as I wanted to.

node-df link: https://www.npmjs.com/package/node-df

var df = require('node-df');

function monitor_json(node, msg) {

var df_str = "";

 df(function (error, response) {
  if (error) { throw error; }
     node.warn(response);
     df_str = response;   
     node.warn(df_str);
 });
        
 node.warn(df_str);
}

Where the "node.warn()" function call logs output in the console.

The node.warn() inside the df function logs the expected result string to the console, while the last node.warn() logs " " in the console. How can I set the df_str variable inside the nested function?

hardillb
  • 54,545
  • 11
  • 67
  • 105
DacHt
  • 3
  • 1
  • I need to ask if the last `node.warn(df_str);` is been called before `df` if yes then `df` is an async function? – Ishank Aug 31 '20 at 14:27
  • How can i check if df is an async function? In the console output the " " output is produced first, then the expected output comes after. – DacHt Aug 31 '20 at 14:33
  • @Klaycon Thank you! As a newbie, the async functionality of javascript is confusing. I appreciate the guidance. – DacHt Sep 01 '20 at 08:39

2 Answers2

0

The challenge you are facing is due to the asynchronous nature of Javascript. The last node.warn(df_str) is potentially executed before df executes the callback that sets df_str. There are many questions on SO about how to wait for a callback before continuing execution. I believe this answer will get you on your way.

Corin
  • 2,317
  • 2
  • 32
  • 47
0

As most of the colleagues here have already mentioned, the problem arises from the asynchronous nature of node. There are multiple ways to tackle this problem. Here is one suggestion:

var df = require("node-df");

const monitor_json = async (node, msg) => {
  const executeDf = () => {
    return new Promise((resolve, reject) => {
      df((error, response) => {
        if (error) reject(error);
        else resolve(response);
      });
    });
  };

  const df_str = await executeDf();
  node.warn(df_str);
};

monitor_json();
atomNULL
  • 209
  • 1
  • 2
  • 6