Issue returning data from inside function - Code Node (JS)

Hey folks,

I’m struggling to work out how to return my data from a code node. I’ve tried returning inside a function (doesn’t return) and doing a push() to a varable outside then returning (remains empty). I can console.log() the data absolutely fine though.

Use case it getting data via httpntlm, as it’s not currently supported by n8n HTTP Request.

let httpntlm = require('httpntlm');
let output = [];

httpntlm.get({
  url: 'https://exampleendpoint/api/data/v9.0/',
  username: 'whatever',
  password: 'watever',
  workstation: '',
  domain: ''
}, function (err, res){
  if(err) return console.log(err);
  let resBody = res.body;
  console.log(resBody); //Console log works perfectly
  return resBody; //Cant return data here for some reason, even if in array.
  output.push(resBody); //Cant push data to output array
});
return output; //This is empty

// Example of data in console log
/*
{
  "@odata.context":"https://exampleendpoint/api/data/v9.0/$metadata",
  "value":[
      {"name":"whatevercollection","kind":"EntitySet","url":"whatevercollection"}
      {"name":"accounts","kind":"EntitySet","url":"accounts"},
      {"name":"aciviewmappers","kind":"EntitySet","url":"aciviewmappers"},
  ]
}
*/

Information on your n8n setup

  • n8n version: 1.81.4
  • Database SQLite
  • n8n EXECUTIONS_PROCESS setting (default: own, main):
  • Running n8n via npm
  • Operating system: MacOS

You are modifying output (with push()) within a promise/callback function. You would need to figure out how to make that synchronous (e.g. put it in an async function and call it with await to make it finish before you reach your return). Not sure whether that is permitted within a code node, but you could try.

async function getEndpointResponse() {
   await httpntlm.get({
        ...
        }, function (...
        ...
    });
}  // end of async function

getEndpointResponse();
return output;

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