How to return an array from async function in Node.js ?
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.
Run the index.js file using the following command:
[ 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.
[ 2, 3, 5, 7, 11, 13, 17, 19 ]