markabrahams / node-net-snmp

JavaScript implementation of the Simple Network Management Protocol (SNMP)
207 stars 97 forks source link

Cant resolve async/await or promise #169

Closed olishr closed 3 years ago

olishr commented 3 years ago

Hello, please someone help, I jsut cant get it. Can you please help on how to make async/await or promise (doneCb), so script waits for first vlc_snmp(..) to finish and then to call next? Example:

function doneCb(error) {
  console.log(final_result);
  final_result = [];
  if (error)
    console.error(error.toString());
}

function feedCb(varbinds) {
  for (var i = 0; i < varbinds.length; i++) {
    if (snmp.isVarbindError(varbinds[i]))
      console.error(snmp.varbindError(varbinds[i]));
    else {
      var snmp_rez = {
        oid: (varbinds[i].oid).toString()
        value: (varbinds[i].value).toString()
      };

      final_result.push(snmp_rez);
    }
  }
}

  var session = snmp.createSession(VLC_IP, "public", options);

  var maxRepetitions = 20;

  function vlc_snmp(OID) {
    session.subtree(OID_, maxRepetitions, feedCb, doneCb);
  }

 vlc_snmp(OID_SERIAL_NUMBER);
 //wait OID_SERIAL_NUMBER to finish and then call next
 vlc_snmp(OID_DEVICE_NAME);
derrell commented 3 years ago

Something along these lines should work. This is untested (and there are a bunch of variables that need real values) but it should give you the idea. The idea is that vlc_snmp must return a promise that resolves or rejects based on the results of the done callback.

let             VLC_IP = "something";
let             options = {};
let             final_result = [];
let             OID_ = "something";
let             OID_SERIAL_NUMBER = "something";
let             OID_DEVICE_NAME = "something";

function feedCb(varbinds) {
  for (var i = 0; i < varbinds.length; i++) {
    if (snmp.isVarbindError(varbinds[i]))
      console.error(snmp.varbindError(varbinds[i]));
    else {
      var snmp_rez = {
        oid: (varbinds[i].oid).toString(),
        value: (varbinds[i].value).toString()
      };

      final_result.push(snmp_rez);
    }
  }
}

  var session = snmp.createSession(VLC_IP, "public", options);

  var maxRepetitions = 20;

  async function vlc_snmp(OID) {
    return new Promise(
      (resolve, reject) =>
      {
        session.subtree(
          OID_,
          maxRepetitions,
          feedCb,
          (e) =>
          {
            if (e) {
              reject(e);
              return;
            }

            resolve();
          });
      });
  }

Promise.resolve()
  .then(() => vlc_snmp(OID_SERIAL_NUMBER))
  .then(() => vlc_snmp(OID_DEVICE_NAME))
  .then(() => console.log(final_result))
  .catch((e) => console.error(e))
  .finally(
    () =>
    {
      final_result = [];
    });
olishr commented 3 years ago

Derrel thank you very much, you saved me a lot of time. Thank you!