Async await inside a custom node

i need to wait for my async function result "on input" event.
Here is my code bellow

module.exports = function (RED) {
  const axios = require('axios');

  function MyNode(config) {

    RED.nodes.createNode(this, config);

  this.on('input', async function (msg) {


  let result = await getDirectory(url).then(
          res=>{
// get undefined
            console.log("Result 1: ", res);
          });
}
}

async function  getDirectory(url){
 await axios.get(url)
      .then(response => {
// Get correct result
        console.log("Result 2: ", response);
        return response;
      })
      .catch(error => {

      });
}

I get a response from the getDirectory function but no response when I subscribe to it.

I think there was a large mix of await, then when there shouldn't be.

try the below.

const axios = require("axios");

module.exports = function (RED) {
  function MyNode(config) {
    RED.nodes.createNode(this, config);

    this.on("input", async function (msg) {
      try {
        let result = await getDirectory(msg.payload.url);
      } catch (Error) {
        // Handle
      }
    });

    function getDirectory(url) {
      return new Promise((resolve, reject) => {
        axios
          .get(url)
          .then((response) => {
            resolve(response);
          })
          .catch((error) => {
            reject(error);
          });
      });
    }
  }
};

Side Note: I updated the tag to async

1 Like

I haven't used axios, but if you can write

axios.get(...).then(...)

it means that get() returns a Promise, which means you can await it.
Thus the whole thing can be condensed into:

    this.on("input", async function (msg) {
      try {
        const result = await axios.get(msg.payload.url);
        // do something with result
      } catch (err) {
        // Handle
      }
    });
1 Like

98% compression ratio :rofl:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.