简体   繁体   中英

How to delay/wait for JSON modification using NodeJS?

I am getting keywords (ExpressJS):

/*
 * GET keywords.
 */
router.get('/keywords', function(req, res) {
    // Check if user is logged in
    if (req.user) {
        var db = req.db;
        var user = req.user;
        db.collection('users').findOne({_id: user._id}, 
            function(err, result) {
                // console.log(result.keywords.RFD);
                res.json(result.keywords.RFD);
            });
    }
});

I am updating my MongoDB (ExpressJS/Mongoose):

/*
 * POST keyword.
 */
router.post('/addkeyword', function(req, res) {
    // Check if logged in
    if (req.user) {
        var db = req.db;
        var user = req.user;
        var keywords = validator.stripLow(validator.trim(req.body.keywords));
        db.collection('users').update({_id: user._id}, {'$addToSet': { 'keywords.RFD' : keywords } }, function(err, result) {
            if (err) throw err;
            if (!err) {
                console.log('Keyword added: ' + keywords);
            };
        }); 
    }
});

The addKeyWord function (JS):

function addKeyword(event) {
event.preventDefault();

// Super basic validation - check if empty
var errorCount = 0;
var keywordRead = $('#addKeyword input#inputKeyword').val();

if($('#addKeyword input').val() === '') { 
    keywordAlert = '<div class="alert alert-danger">Please fill in a keyword.</div>'
    $('#alert').html(keywordAlert);
    return false;
    }
else {
    // If it is valid, compile all user info into one object
    var newKeyword= {
        'keywords': keywordRead,
    }

    // Use AJAX to post the object to our adduser service
    $.ajax({
        type: 'POST',
        data: newKeyword,
        url: '/api/addkeyword',
        dataType: 'JSON',
        success: populateKeywords(true)
    });

}

};

I am populating the page (JavaScript/jQuery):

var keywordContent = '';
$.getJSON( '/api/keywords', function( data ) {
            // For each item in our JSON, add a table row and cells to the content string
            $.each(data.reverse(), function(){
                keywordContent += '<div class="form-group">';
                keywordContent += '<span class="label label-success">' + this + '</span>';
                keywordContent += '<a href="#" class="linkdeletekeyword" rel="' + this + '"> x</a>';
                keywordContent += '</div>';
            }).reverse();
            // Inject the whole content string into our existing HTML table
            $('#myKeywords').html(keywordContent);
        });

The problem is that when I add a keyword, the keywords re-populate, and sometimes the jQuery is too fast and does not list the new keyword.

I would like to add some loading/checking to see if the JSON has changed? The population is only accurate if the /addkeyword is fast enough.

If i understood correctly, you want to populate page only after new keyword addition is complete. As node works on single thread model these issues are likely to occur. No problem with node its just non-blocking way of node. For this kind of stuff i would highly suggest looking at async package of node.

You might have to use something like ,

async.series([
    function(){ ... },
    function(){ ... }
]);
/*
 * POST to addkeyword.
 */
router.post('/addkeyword', function(req, res) {
    // Check if logged in
    if (req.user) {
        var db = req.db;
        var user = req.user;
        var keywords = validator.stripLow(validator.trim(req.body.keywords));
        db.collection('users').update({_id: user._id}, {'$addToSet': { 'keywords.RFD' : keywords } }, 
            function(err, result) {
                if (err) throw err;
                if (!err) {
                    console.log('Keyword added: ' + keywords );
                    // the one line I needed is below:
                    res.end('{"success" : "Updated Successfully", "status" : 200}');
                };
        }); 
    }
});

I've commented above the one line that was missing and that was needed!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM