Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How a Function Returns an Object in JavaScript ?
Next article icon

How to Return an Array from Async Function in Node.js ?

Last Updated : 21 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Asynchronous programming in Node.js is fundamental for handling operations like network requests, file I/O, and database queries without blocking the main thread. One common requirement is to perform multiple asynchronous operations and return their results as an array. This article explores how to achieve this using async functions in Node.js.

Understanding Async Functions

Async functions in Node.js allow you to write asynchronous code that looks and behaves like synchronous code. An async function always returns a promise, and the value returned by the function is wrapped in a resolved promise.

async function example() {
return 'Hello, World!';
}

example().then(console.log);
// Outputs: Hello, World!

Returning an Array from an Async Function

To return an array from an async function, you typically want to collect results from multiple asynchronous operations and return them as an array. Let’s walk through several approaches to achieve this.

Example 1: Below is the code in which we call the print function. We define the array in this function(in this case asynchronous), pass it to another async function sort. The sort function then sorts the array and returns the array, and then we display the array from the print function.

Node
// index.js  const sort = async (arr) => {     try {         let i, j, temp;          // Using bubble sort to sort the array          for (i = 0; i < arr.length; i++) {             for (j = i + 1; j < arr.length; j++) {                 if (arr[i] > arr[j]) {                      // The await prevents the                      // execution of next line                      // until this line is executed                     temp = await arr[i];                     arr[i] = await arr[j];                     arr[j] = await temp;                 }             }         }          // Returns the sorted array         return arr;     }     catch (e) {          // Display the error in case         // anything wrong happened         console.log(e)     } }  const print = async () => {      // Use try-catch block to handle error     try {          // Define and initialize an array         let arr = [17, 90, 13, 10, 76]          // Call the "sort" function passing         // the array and store the result in         // "sortedArray", await will prevent         // the execution of next line until         // this line is executed.         const sortedArray = await sort(arr)          // Display sortedArray to check if          // everything works fine         console.log(sortedArray)     }     catch (e) {          // Display the error in case          // anything wrong happened         console.log(e)     } }  // Calling print() is called print(); 

Run the index.js file using the following command:

node index.js

Output:

[ 10, 13, 17, 76, 90 ]

Example 2: Now let's see the example of returning an array from an async function which has been declared in that async function. The function will return an array of all the prime numbers that are less than a given number N.

Node
// index.js  const prime = async (N) => {     try {         const arr = []          // Iterate from 2 to N-1 to check         // which numbers are prime         for (var i = 2; i < N; i++) {             let j = 2             while (j < i) {                 // Check if the number is                  // divisible by any number                 // except 1 and itself                 if (i % j == 0) {                     break                 }                 j++;             }             if (j == i) {                 // If this condition holds                  // true then it means that                 // the number is not                  // divisible by any number                 // except 1 and itself.                  // Therefore, it is a prime                  // number and add this number                 // to the array.                 arr.push(j)             }         }          // Return the array         return arr     }     catch (e) {          // Display the error in case         // anything wrong happened         console.log(e)     } }  const findPrime = async () => {     try {         let N = 20          // Call prime() passing argument         // N which is equal to 20 and          // store the result in an array         const primeAry = await prime(N)          // Print the array         console.log(primeAry)     }     catch (e) {                  // Display the error in case         // anything wrong happened         console.log(e)     } }  // Calling findPrime() method findPrime() 

Output
[    2,  3,  5,  7,   11, 13, 17, 19 ] 

Example 3: When dealing with multiple asynchronous operations, you can use Promise.all to execute them in parallel and collect their results into an array.

Node
// index.js  async function fetchData() {   const promise1 = new Promise(resolve => setTimeout(() => resolve('data1'), 1000));   const promise2 = new Promise(resolve => setTimeout(() => resolve('data2'), 500));   const promise3 = new Promise(resolve => setTimeout(() => resolve('data3'), 2000));    const results = await Promise.all([promise1, promise2, promise3]);   return results; }  fetchData().then(console.log);  

Outputs:

[ 'data1', 'data2', 'data3' ]



Next Article
How a Function Returns an Object in JavaScript ?

R

rupalics18
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • NodeJS-Questions

Similar Reads

  • How to return an array of lines from a file in node.js ?
    In this article, we will return an array of lines from a specified file using node.js. The fs module is used to deal with the file system in node.js and to read file data we use fs.readFileSync( ) or fs.readFile( ) methods. Here we will use the readFileSync method to read the file, and we use the st
    2 min read
  • How to execute an array of synchronous and asynchronous functions in Node.js?
    We have an array of functions, some functions will be synchronous and some will be asynchronous. We will learn how to execute all of them in sequence. Input: listOfFunctions = [ () => { console.log("Synchronous Function); }, async () => new Promise(resolve => { setTimeout(() => { resolve
    2 min read
  • How to convert an asynchronous function to return a promise in JavaScript ?
    In this article, we will learn how to convert an asynchronous function to return a promise in JavaScript. Approach:  You need to first declare a simple function (either a normal function or an arrow function (which is preferred)). You need to create an asynchronous function and then further you need
    3 min read
  • How to Write Asynchronous Function for Node.js ?
    The asynchronous function can be written in Node.js using 'async' preceding the function name. The asynchronous function returns an implicit Promise as a result. The async function helps to write promise-based code asynchronously via the event loop. Async functions will always return a value. Await
    2 min read
  • How a Function Returns an Object in JavaScript ?
    JavaScript Functions are versatile constructs that can return various values, including objects. Returning objects from functions is a common practice, especially when you want to encapsulate data and behavior into a single entity. In this article, we will see how a function returns an object in Jav
    3 min read
  • How to Type an Async Function in TypeScript ?
    An asynchronous function allows your code to do multiple things at once. It doesn't block the execution of the rest of your code while waiting for a long task (like reading a file, making an API request) to finish. Instead, it returns a Promise, making it easier to handle operations that might take
    3 min read
  • How to create an Asynchronous function in Javascript?
    JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time. But Javascript may appear to be asynchronous in some situations. Example: C/C++ Code <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" />
    6 min read
  • How to Push Data to Array Asynchronously & Save It in Node.js ?
    Node.js is a powerful environment for building scalable and efficient applications, and handling asynchronous operations is a key part of its design. A common requirement is to collect data asynchronously and store it in an array, followed by saving this data persistently, for instance, in a databas
    6 min read
  • How to access object properties from result returned by async() function in JavaScript ?
    In this article, we will see how to access the properties of a javascript object result returned by the async() function in Javascript. A javascript object property is a variable that is associated (read attached) with the object itself, i.e. the properties have a name and value is one of the attrib
    3 min read
  • How to convert function call with two callbacks promise in Node.js ?
    Promise: Promise is used to handle the result, if it gets the required output then it executes the code of then block, and if it gets the error then it executes the code of the catch block. A promise looks like this - function() .then(data => { // After promise is fulfilled console.log(data); })
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences