在循环中向worklight jsonstore添加文档

adding documents to worklight jsonstore in a loop

本文关键字:jsonstore 添加 文档 worklight 循环      更新时间:2023-09-26

我想动态生成列表条目,并同时将它们作为jsonstore文档添加到我的本地存储

当我这样做的时候:

     var j=0;
       while(j<7) {
        /* populating our jsonstore */   
        accessor.add({stuff_to_add})
        .then(function(){})
        /* showing it to the user */
        $('<li>').attr({attributes}).html('html').appendTo('element');   
        j++;
       }

只添加一个文档,因为我认为worklight不会自动将添加请求放入队列中,并且如果前面的请求没有解决或沿着这些行取消最后一个。

所以当我这样做的时候:

      var j=0;
       while(j<7) {
        /* populating our jsonstore */   
        accessor.add({stuff_to_add})
        .then(function(){
        /* showing it to the user */
        $('<li>').attr({attributes}).html('html').appendTo('element');   
        j++;   })
       }

Mozilla完全崩溃了,甚至没有成功停止脚本,我不明白为什么,因为它应该只调用add函数几次=(调用(accessor.add)的时间/循环的时间),这应该是有限的。

编辑:实际上,如果我们假设worklight没有将文档放入添加队列中,则每次循环循环时初始添加请求都会被替换,并且它永远不会完成,这解释了崩溃。

编辑2:尝试使用递归函数调用自身直到j达到7,而不是循环

编辑2:

var j=0;
       while(j<7) {
        /* creating the ui*/
        $('<li>').attr({attributes}).html('html').appendTo('element');
        j++;
       }
       /* populating jsonstore */
      add_documents(0,stuff_to_add);

其中add_documents(0,stuff_to_add)定义如下:

add_documents = function(n,stuff_to_add){ 
    if(n<7){
        accessor.add({stuff_to_add})
        .then(function(){alert(n);add_documents(n+1,stuff_to_add);});
    }
    else
    {return true;}
};

add API可以接受JSON对象数组,例如:

var data = [{name: 'carlos'}, {name: 'mike'}];
WL.JSONStore.get('collection').add(data)
.then(function () {
  /*update the UI here*/
  var len = data.length;
  while (len--) {
    console.log(data[len].name);
  }
})
.fail(function (err) {
  /*handle failure*/
});