0

I am building an application in NodeJS version 8.5 with Express middleware.

I am using the async module to loop over an array of objects. The async.each method iterates over each object and processes each element.

Each object will be processed in a different way depending upon the property.

The way I have it now is to just call a bunch of synchronous methods inside the body of the async.each loop. However, I know that this isn't the 'proper' Node way since everything supposed to be asynchronous.

How can I structure this to use asynchronous methods properly?

async.each(elements_all, (element_original, callback) => {
  // Create new array
  const elements_processed = [];

  // If element has order number property
  if (element_original.order_number) {
    element_original.order_number = processToDisplay(element_original.order_number); //This is a synchronous call
  }

  // If element has po number property
  if (element_original.po_number) {
    element_original.po_number = processToDisplay(element_original.po_number);
  }

  // If element has item price property
  if (element_original.item_price) {
    element_original.item_price = processToDisplay(element_original.item_price);
  }

  // Push to the return array
  entities_processed.push(element_original);

  callback();
}, (err) => { 
  if (err) {
    res.json({
      server_error: true
    });
  } else {
    res.json(entities_processed);
  }
});
5
  • 2
    Uh, if you have no genuinely asynchronous work to do, then it's not asynchronous and you should just use a synchronous loop. Commented Feb 22, 2018 at 22:51
  • is processToDisplay the async part? Commented Feb 23, 2018 at 0:24
  • @forJ processToDisplay is a synchronous method and I was thinking that I would need to convert that into an asynchronous method, since it is inside the body of an async.each loop iteration. I have read that you should 'never call sync methods inside of an async method' in NodeJS. Commented Feb 23, 2018 at 14:19
  • I think I found a good answer here. stackoverflow.com/questions/25137461/… There are many examples that use synchronous calls inside the body of async.each method so I suppose the way I have it now is acceptable. Commented Feb 23, 2018 at 16:05
  • 1
    You can also make sync process async by spawning another process Commented Feb 24, 2018 at 0:57

0

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.