How to return an array from async function in Node.js ?
Last Updated :
05 Jan, 2023
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;
for (i = 0; i < arr.length; i++) {
for (j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
temp = await arr[i];
arr[i] = await arr[j];
arr[j] = await temp;
}
}
}
return arr;
}
catch (e) {
console.log(e)
}
}
const print = async () => {
try {
let arr = [17, 90, 13, 10, 76]
const sortedArray = await sort(arr)
console.log(sortedArray)
}
catch (e) {
console.log(e)
}
}
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.
index.js
const prime = async (N) => {
try {
const arr = []
for ( var i = 2; i < N; i++) {
let j = 2
while (j < i) {
if (i % j == 0) {
break
}
j++;
}
if (j == i) {
arr.push(j)
}
}
return arr
}
catch (e) {
console.log(e)
}
}
const findPrime = async () => {
try {
let N = 20
const primeAry = await prime(N)
console.log(primeAry)
}
catch (e) {
console.log(e)
}
}
findPrime()
|
Output:
[
2, 3, 5, 7,
11, 13, 17, 19
]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...