1

I have an array, like [1,2,3,4,5,6,7,8,10].

I like to process one item at a time. synchronously.

I have mixed with non-async functions too.

var array = [1,2,3,4,5,6,7,8,9,10]
for(i=0; i< array.length; i++){
    var result = await fun1(array[i]);
    console(result) //expecting print out 2,4,6,8,10...20 synchronously
}

async function fun1(item){
    return fun2(item);
}
async function fun2(item){
    a = new A(item)
    return a.hello()
}

class A{
    constructor(item){
       this.item = item;
    }

    hello(){
        //do something
        return this.item * 2;
    }
}

How can I make it happen in Node.JS?

1 Answer 1

2

you can use Promise.all feature.

const promises = [];
const array = [1,2,3,4,5,6,7,8,9,10]
array.forEach((num)=>{
  promises.push(func1(num))
});

Promise.all(promises)
.then(response => console.log(response)); // your required response
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.