Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent statement to 'continue' when using node.js async forEachSeries?

I am using the node.js async package, specifically forEachSeries, to make a series of http requests based on parameters drawn from an array. In the callback of each request I have some if/else statements to respond to different types of responses.

// This is the callback of a GET request inside of a forEachSeries
function(error, response) {
    if (response.results) {
        // Do something with results
    }
    else if (!response.results) {
        // Would like to use a continue statement here, but
        // this is not inside of a loop
    }
    else {
        // Do something else
    }
}

Is there an equivalent to 'continue' that I can use inside of the else if above? This is not technically inside of a loop so continue does not work.

like image 937
TankofVines Avatar asked Apr 11 '12 13:04

TankofVines


People also ask

How does node JS achieve asynchronous?

Node. js uses callbacks, being an asynchronous platform, it does not wait around like database query, file I/O to complete. The callback function is called at the completion of a given task; this prevents any blocking, and allows other code to be run in the meantime.

Can I make a forEach async?

forEach is not designed for asynchronous code. (It was not suitable for promises, and it is not suitable for async-await.) For example, the following forEach loop might not do what it appears to do: const players = await this.

Can you await in a for loop?

You need to place the loop in an async function, then you can use await and the loop stops the iteration until the promise we're awaiting resolves. You could also use while or do.. while or for loops too with this same structure. But you can't await with Array.


1 Answers

Since it is just a function you should be able to return from it to have the same effect:

else if (!response.results) {
    return;
}
like image 168
Justin Ethier Avatar answered Oct 23 '22 05:10

Justin Ethier