What is the reason for JavaScript to return an empty array?

How can I handle asynchronous operations in JavaScript to prevent my callback from returning an empty array? Here's the code snippet:

function getPicturesArray(nbr, callback){
    var avatarArr = [];
    for(var i = 0; i < nbr; ++i){
        request("https://randomuser.me/api/", {json: true}, (err, response, body) => {
            avatarArr.push(body.results[0].picture.large);
        });
    }
    callback(avatarArr);
}

getPicturesArray(12, (e) => {
    console.log(e);
});

console.log('here');

The output is: [] here

Answer №1

For the sake of demonstration, I am simulating calls with a public service to highlight the asynchronous nature of HTTP requests.

Even though your for loop is complete when you invoke callback(avatarArr);, the requests (12 in this example) sent out are still pending, resulting in an empty avatarArr.

Note the presence of async before function getPicturesArray and await before fetch

The await keyword instructs the program to wait for the completion of the fetch call

It's imperative that you familiarize yourself with async/await.

async function getPicturesArray(nbr,callback){
    var avatarArr = [];
    console.log('loading...');
    for(var i =0; i<nbr ; ++i){
      const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${i+1}`);
      const json = await response.json();
      avatarArr.push(json.title);  
    }
    console.log('done loading...');
    callback(avatarArr);
}

getPicturesArray(12, (e)=>{
    console.log(e);
});

console.log('see how this is executed before done loading...');

Answer №2

Implement Promises or async/await instead of using callbacks.

  getUserPic = async () => {
    const url = 'https://randomuser.me/api/'
    const response = await fetch(url)
    const users = await response.json()

    return users.results[0].picture.large
  }
  ;(async () => {
    const userAvatars = []
    for (let i = 0; i < 12; i++) {
      userAvatars.push(await getUserPic())
    }
    console.log(userAvatars)
  })()

Consider using Set instead of Array to avoid duplicate items in the collection.

  getUserPic = async () => {
    const url = 'https://randomuser.me/api/'
    const response = await fetch(url)
    const users = await response.json()

    return users.results[0].picture.large
  }

  getMultipleUserPics = async limit => {
    const userAvatars = new Set()
    while (userAvatars.size != limit) {
      userAvatars.add(await getUserPic())
    }

    return userAvatars
  }

  ;(async () => {
    const userPics = await getMultipleUserPics(5)
    console.log(userPics)
  })()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the purpose of $winstonLoggerConfig<T>() and $winstonLogger<T>() in winston v3?

I'm currently using the winston logger and I want to implement flow typing for it. However, I am unsure of what exactly I should pass to it in order to achieve this. Below is my current logger setup: const logger = createLogger({ ... }); Missing typ ...

"Encountered an error while trying to access properties that

Struggling to create a practice menu with the functionality of making elements appear and disappear on click? If you are encountering issues with a class named "option" not working as expected, you are not alone. Clicking on nested objects like images or i ...

Is there a way to transfer JSON data from a JSP page to a Spring REST controller efficiently?

Attempting to send data from a jsp page containing datetime, zoneid, checked checkboxes with values, and unchecked checkboxes with null values. Despite sending all this as json to my spring rest controller, I noticed in debug mode that the controller only ...

Converting an Array with Key-Value pairs to a JSON object using JavaScript

After using JSON.stringify() on an array in JavaScript, the resulting data appears as follows: [ { "typeOfLoan":"Home" }, { "typeOfResidency":"Primary" }, { "downPayment":"5%" }, { "stage":"Just Looki ...

How does NodeJs handle ongoing tasks and processes seamlessly?

One interesting concept is the Event Loop, which accepts callbacks and executes them as needed. As far as I understand, this operates on a single thread event loop, meaning only one callback is executed at a time. Consider the following example: setInterv ...

Leveraging the Spread Operator in Redux mapDispatchToProps with SweetAlert2

When I add the swal action creators to the mapDispatchToProps function like this: function mapDispatchToProps(dispatch) { return { getAnimal: (_id) => dispatch(getAnimal(_id)), ...swal } } The issue aris ...

Having Trouble with My Array Key Value Multiplication Script

Hey there, this is my first time posting here. I'm relatively new to PHP and Perl, so please forgive any obvious mistakes you may spot in the script below. I've written a script to scrape a bank's asset amount, apply a 3% increase, and disp ...

Acquiring profile information in intricate scenarios using passport-facebook with node.js

I'm currently working with the passport-facebook package, but I've encountered an issue with the way it's usually implemented: app.get('/oauth/facebook', passport.authenticate('facebook', {})); This approach doesn' ...

What could be causing the code to malfunction and prevent window.ethereum from working properly?

While attempting to develop a dApp, I have encountered an issue with the browser in Visual Studio Code not recognizing the Ethereum connection, despite having installed MetaMask on the active browser session. Here is a snippet of my code used to test the c ...

Issues with jQuery show and hide functionality are not performing as expected

A dazzling animation has been created, fading in and out gracefully. With two buttons at hand $('.point li') to reveal distinct contents $("#"+classVal+" .table-cell") Nevertheless, upon clicking $('.point li'), I aspire for its conte ...

Each keystroke is saved individually in an array, thanks to React, instead of storing the entire text

Hey everyone, I have a task to develop a full-stack web application that allows users to create meals with ingredients, preparation details, and cooking time. I am using MongoDB, Node.js, Express, and React for this project. Everything works fine when test ...

Utilizing a Jackson-inspired library for handling JSON property names containing dots in Javascript

Is there a way to create a Json with field names that contain dots '.' in a JavaScript application (specifically, TypeScript)? This is the expected Json output: { "tasks.max": "1", "key.converter": "io. ...

Retrieve the property of an object from within an array

I am dealing with an array structure like this: const arr = [{ name: 'One', id: 1 }, { name: 'Two', id: 2 } ]; My goal is to extract and return the name of the object if its id matches a certain value. After exp ...

"Create a smooth transition effect in CSS by fading out one div and fading in

I've set up a grid of buttons, and my goal is to have the grid fade out when a button is clicked, then fade in with a new div in its place. This involves animating opacity from 1 to 0 and vice versa while toggling the display:none property for content ...

What is C++'s perspective on understanding Arrays as pointers?

After working on some code, I encountered an issue with returning a two-dimensional array that resulted in an error message being thrown. int (* function (int input[2][2]) ) [2][2]{ return input; } https://i.sstatic.net/Y3ojS.png Throu ...

Managing API responses and notifications within a Redux store: tips and best practices

Every time I trigger an action, I want to make sure that the API response is checked before displaying a success message. For example, in the function below where I delete an item using react-redux dispatch: dispatch(deleteItemID(itemId)); notify.show(&quo ...

The JSON page does not display the image

I am facing an issue where the images are not displaying on both the JSON page and the HTML page, even though the image source name is being outputted. How can I ensure that the images show up on the HTML page? Thank you for taking the time to help. line ...

Understanding the implementation of public and private methods in mixins in Vue2

While I've come across documentation on the following implementation, I find myself struggling to visualize how it can be executed. // A more advanced alternative! var myGreatMixin = { // ... methods: { publicMethod() { // ... myPr ...

Can a single controller function in ASP.NET MVC4 be used to send back two arrays to the view?

Continuing from my previous query here, I am working with a model called SchoolTestsPerModulePerStudent which looks like this: public partial class SchoolTestsPerModulePerStudent { public long StudentID { get; set; } public long ModuleID { get; se ...

Populating PHP array using a "for" loop

In PHP, I am attempting to populate an array in the following manner: <?php $maxPages = 20; for ($i = 0; $i <= $maxPages; $i++) { $url = 'http://127.0.0.1/?page='.$i; $targets = array( $url => array( ...