0

While learning Node.js and after some trial and error I have this working code that makes API calls to retrieve user records where each API call is dependent on the result of the previous API call.


const axios = require('axios')

var getDataById = async (config) => {
    var response = await axios(config);
    var userById = {};
    userById['userId'] = response.data["userId"];
    return(userById);
};

(async () => {
    var a = []; // array for storing user data
    var userId = '0001';

    var done = false; // false until user '0010' is reached

    while (!done) {
        url = "https://someurl.com/" + userId;

        var axiosconfig = {
            method: 'get',
            url: url,
            headers: {
                'Authorization': 'Bearer SECRET_TOKEN'
            }
        };

        var userDataById = await getDataById(axiosconfig);  
        a.push(userDataById);
        
        userId = userDataById['userId'];

        if (userId == '0010') { done = true }
    }

})()

How can I call this code from elsewhere in my program in such a way that

  1. I can pass arguments to it...for example 'userId'
  2. I can return 'a' to the calling function
  3. the calling function waits for 'a' to be returned before continuing

TBH, I don't quite get how this works.

;(async () => {})()

Is there a better way of coding this?

user8865059
  • 71
  • 2
  • 13
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – derpirscher Oct 20 '22 at 22:08

1 Answers1

0

You need to create an async function and then await it.

The function definition will look like this

async function AddUser(userId)

You can return any variable and you call it like this:

await addUser('002')

await keyword make sure that the calling function waits for 'a' to be returned before continuing.

For your last question:

(async () => {})()

Is an arrow function.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Using async keyword + arrow function is a trick to allow you to create an async context and being able to use await. The two last () are used to direct call this function.

CptHash
  • 1
  • 2