Call a function with an async method in another script

Hi all, I’m having trouble with returning data from an async function when calling it from another script.

So basically, I have the following structure:

script_one.js

const curl_site = require('./script_two');
(async () => {
		try {
			const response = await curl_site(req.body.name);
			console.log(response);
		} catch (error) {
			console.log(error);
		}
	})();

And then the second script which holds the async function:
script_two.js

const got = require('got');

function getInfo(url) {
	(async () => {
		try {
			const response = await got(url);
			let data = response;
			return data;
		} catch (error) {
			console.log(error);
			//=> 'Internal server error ...'
		}
	})();
}

module.exports = getInfo;

As you can see, the function getInfo has an “url” as a paramter which gets passed in the first script.
But the “data” is always returning undefined. When I actually try to console log the “response” variable, it returns all the data I want, but doesn’t pass the info to the other script. How can I return data from an async function?

Hi @silic5494, you’re not returning anything from getInfo() – the function just calls another anonymous async function, ignoring its return value. So you have to return the result of that IIFE:

function getInfo(url) {
  return (async () => {
    // ...
  })()
}

Actually the IIFE isn’t even necessary here though:

async function getInfo(url) {
  try {
    return await got(url)
  } catch (error) {
    console.error(error)
  }
}
1 Like

Well, as it turns out. I was doing it wrong xD
Doing it like this worked:
script_one.js

	async function getRes() {
		const response = await curl_site(req.body.name);
		console.log(response);
	}
	getRes();

script_two.js

async function getInfo(url) {

const response = await got(url);

return response;

}

Thank you! This works too!

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