Why is this operation myFunction (). Then () seems to hang endlessly?

I'm having some problems with the NON PRODUCTION code. I want to process about 3000 elements of an array. If I execute the node process, it sits in epoll_wait(5 , so, apparently, I am blocking the main thread.

Can anyone suggest either a) what I'm doing wrong, or b) how can I look at the run loop / run loop to see exactly why the code hangs? I tried to debug and execute the code, and this process works, but I'm not wiser.

UPDATED code using Promises.map:

 connection.query(firstPostQuery,{ x: whiteListString }, function( err, rows ) { Promise.map(rows, function(result) { return sfs.isSpammer({ ip: result.ip, email: result.email, username: result.poster }).then(function(res) { console.log(parseInt(res.username.appears) == 1); //evaluates to true if (parseInt(res.username.appears) == 1 ) { console.log(res.toJSON()); fs.appendFile(__dirname + '/stopforumspam.txt', res.poster + '\n', function(err) { if (err) { throw err; } return true; }); } else { fs.appendFile(__dirname + '/stopforumspam.txt', 'nope\n', function(err) { if (err) { throw err; } return true; }); } }); //Iteration completed }, {concurrency: 5}).then(function(result) { //Do something with result console.log(result); }).catch(function(err) { //Error }); }); 

I am running against node.js 4.2.4. I experimented with Bluebird promises, but I'm not sure if this would be useful in this case, as I do not fully understand promises (for now).

+8
source share
1 answer

You can try using (bluebird) Promise.map to iterate async.

 connection.query(firstPostQuery, {x: whiteListString}, function(err, rows) { Promise.map(rows, function(result, index) { console.log('item', index); return new Promise(function(resolve, reject) { sfs.isSpammer({ ip: result.ip, email: result.email, username: result.poster }).then(function(res) { console.log('In Promise', res); console.log(parseInt(res.username.appears) == 1); //evaluates to // true if (res && parseInt(res.username.appears) == 1) { return fs.appendFile(__dirname + '/stopforumspam.txt', res.poster + '\n', function(err) { console.log('In AppendFile spamer'); if (err) { reject(err); } resolve(true); }); } else { return fs.appendFile(__dirname + '/stopforumspam.txt', 'nope\n', function(err) { console.log('In AppendFile good user'); if (err) { reject(err); } resolve(true); }); } }); }); }).then(function(res) { console.log(res); }).catch(function(err) { console.log(err); }); }); 
+1
source share

All Articles