How to return an array from async function in Node.js ?

01 Jul, 2021
We have to call the async function from another function which can be asynchronous or synchronous (We can pass the array or choose to declare the array in the async function itself) and then return the array from the async function.
The basic approach is to include a try-catch block. If anything wrong happens while executing the try block statements, then a catch block is used to handle the exception.
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.
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        // enything 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 calledprint();
 
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.
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                 // divisble 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() methodfindPrime()
Output:
[
   2,  3,  5,  7,
   11, 13, 17, 19 
]
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.