如何使用NodeJS延迟/等待JSON修改?

时间:2014-08-07 02:47:56

标签: javascript node.js mongodb express mongoose

我正在获取关键字(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);
            });
    }
});

我正在更新我的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);
            };
        }); 
    }
});

addKeyWord函数(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)
    });

}

};

我正在填充页面(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);
        });

问题在于,当我添加关键字时,关键字重新填充,有时jQuery太快而且没有列出新关键字。

我想添加一些加载/检查以查看JSON是否已更改?只要/ addkeyword足够快,人口才是准确的。

2 个答案:

答案 0 :(得分:0)

如果我理解正确,您只想在新关键字添加完成后填充页面。由于节点在单线程模型上工作,因此很可能会出现这些问题。节点没有问题,它只是节点的非阻塞方式。对于这种东西,我强烈建议查看async节点包。

你可能需要使用像

这样的东西
async.series([
    function(){ ... },
    function(){ ... }
]);

答案 1 :(得分:0)

/*
 * 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}');
                };
        }); 
    }
});

我在上面评论了缺失的一行,这是必要的!