如何使用JSOM在SharePoint列表中插入超过5000个项目?

时间:2017-12-08 03:56:24

标签: sharepoint sharepoint-2013 sharepoint-list sharepoint-jsom

我正在尝试使用JSOM在SharePoint列表中添加5000个项目。但遗憾的是没有运气。

function createListItem() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('DummyList');

    var itemCreateInfo = new SP.ListItemCreationInformation();
    for (var i = 0; i < 5000; i++) {
        this.oListItem = oList.addItem(itemCreateInfo);

        oListItem.set_item('ItemNumber', i);
        oListItem.update();
    }

    clientContext.load(oListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
    console.log('Item created: ' + oListItem.get_id());
}

function onQueryFailed(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

但是经过一段时间服务器停止响应。我知道有一种称为阈值限制的东西。但根据要求,一次只能存储5000多件物品。我不知道我在哪里弄错了。请帮忙。

3 个答案:

答案 0 :(得分:0)

这是一个建议。它确实适用于我的环境。它需要一些时间(大约20秒),因为所有请求都由服务器排队。您可以使用批量限制来优化请求数量。

function createListItem() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('DummyList');

    var items = [];
    var batchLimit = 100;

    for (var i = 0; i < 5000; i++) {
        var itemCreateInfo = new SP.ListItemCreationInformation();
        var newItem = oList.addItem(itemCreateInfo);

        newItem.set_item('ItemNumber', i);
        newItem.update();
        items[i] = newItem;
        clientContext.load(items[i]);

        if (i % batchLimit == 0) {
            console.log("sending batch" + i / batchLimit);                                
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
            items = [];
        }            
    }
}

function onQuerySucceeded() {
    console.log('Item created');
}

function onQueryFailed(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

答案 1 :(得分:0)

不知何故,我找到了解决方案。而不是回调方法,我使用像这样的REST API

function RestAdd()
{

      for(var i = 0 ; i < 5000; i++)
      {
$.ajax  
    ({  
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('DummyListForMultiAdd')/items",  
    type: "POST",
    async: false,
    data: JSON.stringify  
    ({  
        __metadata:  
        {  
            type: "SP.Data.DummyListForMultiAddListItem"  
        },  
        ItemNumber: i
    }),  
    headers:  
    {  
        "Accept": "application/json;odata=verbose",  
        "Content-Type": "application/json;odata=verbose",  
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
        "X-HTTP-Method": "POST"  
    },  
    success: function(data, status, xhr)  
    { 
    console.log("success: "+i);
    },  
    error: function(xhr, status, error)  
    {  
        console.log("failed: "+i);
    }  
});
}
}

我所做的是,我只使用了async:false的REST API。它以同步方式添加您的列表项。在JSOM中,它可以在异步中工作。

答案 2 :(得分:0)

这是两种技术的结合。

async function createListItem() {
  const url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('DummyListForMultiAdd')/items`;
  for (let index = 0; index < data.length; index += 100) {
    const finalNumber = index + 100 < data.length ? index + 100 : data.length;
    const batch = data.slice(index, finalNumber);
    const batchPromises = batch.map((d, i) => {
      d.__metadata = {
        type: "SP.Data.DummyListForMultiAddListItem"
      };
      d.ItemNumber = i + index;
      return xhr("post", url, d);
    })
    await Promise.all(batchPromises);
  }

  function xhr(type, url, data) {
    const prom = new Promise((res, rej) => {
      const xhr = new XMLHttpRequest();
      xhr.onreadystatechange = () => {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          try {
            if (xhr.status === 200 || xhr.status === 201) {
              res(xhr.responseText);
            } else {
              const {
                status
              } = xhr;
              const name = "XHRError";
              const message =
                xhr.responseText ||
                "An error occured in sending or recieving the request";
              throw {
                status,
                name,
                message
              };
            }
          } catch (error) {
            if (error.status) {
              rej(error);
            } else {
              rej({
                status: 418,
                name: error.name,
                message: error.message
              });
            }
          }
        }
      };
      xhr.open(type, url);
      [{
          key: "Accept",
          value: "application/json;odata=verbose"
        },
        {
          key: "Content-Type",
          value: "application/json;odata=verbose"
        },
        {
          key: "X-RequestDigest",
          value: document.querySelector("#__REQUESTDIGEST").value
        }
      ].forEach(h => xhr.setRequestHeader(h.key, h.value));
      xhr.send(JSON.stringify(data));
    });
    return prom;
  }
}
createListItem()