Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/477.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用NodeJS延迟/等待JSON修改?_Javascript_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

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

Javascript 如何使用NodeJS延迟/等待JSON修改?,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,我得到关键词(ExpressJS): 我正在更新我的MongoDB(ExpressJS/Mongoose): addKeyWord函数(JS): 函数addKeyword(事件){ event.preventDefault(); //超级基本验证-检查是否为空 var errorCount=0; var keywordRead=$('#addKeyword input#inputKeyword').val(); if($('#addKeyword input').val()=''){ keywo

我得到关键词(ExpressJS):

我正在更新我的MongoDB(ExpressJS/Mongoose):

addKeyWord函数(JS):

函数addKeyword(事件){
event.preventDefault();
//超级基本验证-检查是否为空
var errorCount=0;
var keywordRead=$('#addKeyword input#inputKeyword').val();
if($('#addKeyword input').val()=''){
keywordAlert='请填写关键字。'
$('#alert').html(关键字alert);
返回false;
}
否则{
//如果有效,则将所有用户信息编译为一个对象
var newKeyword={
“关键词”:关键字阅读,
}
//使用AJAX将对象发布到我们的adduser服务
$.ajax({
键入:“POST”,
数据:newKeyword,
url:“/api/addkeyword”,
数据类型:“JSON”,
成功:populateKeywords(真)
});
}
})

我正在填充页面(JavaScript/jQuery):

var关键字content='';
$.getJSON('/api/keywords',函数(数据){
//对于JSON中的每个项目,向内容字符串添加一个表行和单元格
$.each(data.reverse(),function()){
关键词内容+='';
关键词content+=''+此+'';
关键词内容+='';
关键词内容+='';
}).reverse();
//将整个内容字符串注入到现有的HTML表中
$('#myKeywords').html(关键字内容);
});
问题是,当我添加关键字时,关键字会重新填充,有时jQuery速度太快,并且没有列出新关键字


我想添加一些加载/检查,看看JSON是否已更改?只有在/addkeyword足够快的情况下,填充才是准确的。

如果我理解正确,您希望仅在新关键字添加完成后填充页面。当节点在单线程模型上工作时,这些问题很可能会发生。节点没有问题,只是节点的非阻塞方式。对于这类内容,我强烈建议查看节点包

你可能需要使用类似的东西

async.series([
    function(){ ... },
    function(){ ... }
]);
我已经在上面评论了一行遗漏的内容,这是需要的

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

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