How to exit callback loop in javascript

I have a simple codesnippet in a file test.js:

[1, 2, 3, 4].forEach(function(e) {
    console.log(e);
});

whenever I run node test.js in terminal I get the output

1
2
3
4
|

But the program never really exits. I am required to end it manually. Seems quite trivial but I am unable to figure out a proper way to exit the scrip in the terminal.

UPDATE 1:

var mongoose = require('mongoose');

var User = require('../models/users/user');
var UserProfile = require('../models/users/profile');

var config = require('../config');
var logger = require('../libraries/logger');
logger = logger.createLogger(config);

var connectionString = config.database.adapter + '://' + config.database.host + ':' + config.database.port + '/' + config.database.name;
mongoose.connect(connectionString, {server: {auto_reconnect: true }});

User.find(function(error, users) {
    users.forEach(function(user) {
    var data = {
        email: user.local.email || user.google.email || user.facebook.email || ''
    };
    UserProfile.update({user_id: user._id}, {$set: data}, function (error, record) {
        if (error) {
            logger.error(error);
        } else {
            logger.info(data);
        }
    });
});

Above is the code I am actually trying to make work. Adding process.exit() exits the process even without processing the script. Any solutions?

UPDATE 2: I figured out the solution. In above case script wasn't exiting because connection to mongodb database wasn't closed.

I used a dirty hack to close the connection after processing is done by adding setTimeout(function() { mongoose.connection.close(); }, 60 * 1000); at the end of the line


If this is a nodejs question which it appears to be then you exit using process.exit() so you add that to the end of whatever function should run last. In your case you would close mongoose first and hen have the process.exit() as the success handler for the exiting of mongoose

链接地址: http://www.djcxy.com/p/52718.html

上一篇: 如何在nodejs中运行独立的bash脚本

下一篇: 如何退出JavaScript中的回调循环