如何让ExecuteQueryAsync更加同步?

jaz*_*ict 3 javascript sharepoint jquery

Aight ..这个Sharepoint使用Javascript ..我正在使用警报来调试从内容编辑器Web部件运行的Javascript; 该脚本位于Assets库中.

我明白了......"异步"函数调用的全部要点是不要等待完成调用....但我担心ExecuteQueryAsync中的操作将在以后完成错误......

我很确定,因为我的警报输入和警报返回"向后",我确实得到了我的异步行为.我尝试了没有"异步"部分的"ExecuteQuery"......这真失败了.

在返回OBJ功能之前,有人想要朝着正确的方向努力,让我的ONSUCCESS功能中的活动完成.

function One()
{
alert("in ONE");
OBJ();
alert("back from Obj, in One Again");
}

function OBJ(){
alert("in OBJ");
 var clientContext = null; 
 var currentweb = null; 
        clientContext = new SP.ClientContext.get_current(); 
        web = clientContext.get_web(); 
        var Questionlist = web.get_lists().getByTitle("Exam Objectives"); 
        var camlQuery = new SP.CamlQuery();
        var q = "";    //camlQuery text in q to limit colls returned, empty string returns all
        camlQuery.set_viewXml(q); 
        this.listItems = Questionlist.getItems(camlQuery); 

        clientContext.load(listItems);
         clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemsLoadSuccessObj), Function.createDelegate(this,         this.onQueryFailed)); 
 alert("leaving OBJ");    //THIS ALERT FIRES BEFORE THE ALERT BELOW********
 }

function onListItemsLoadSuccessObj(sender, args) { 
 var listItemInfo = '';
 var oListItem = null;
var listItemEnumerator = listItems.getEnumerator();

while (listItemEnumerator.moveNext()) {
    oListItem = listItemEnumerator.get_current();
    listItemInfo += '\nID: ' + oListItem.get_id() + 
        '\nTitle: ' + oListItem.get_item('Title');
}

alert(listItemInfo.toString());  //THIS ALERT FIRES AFTER THE ALERT ABOVE*********     
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 8

你想看看Promises.Scot Hillier在这里写得很好:http://www.shillier.com/archive/2013/03/04/using-promises-with-the-javascript-client-object-model-in-sharepoint-2013.aspx但基本上他们允许你编写这样的代码:

doSomething()
.then(doSomethingElseWhenThatsDone, orHandleAnError)
.then(doYetAnotherThingWhenThatsDone, orHandleAnError);
Run Code Online (Sandbox Code Playgroud)

你调用的函数(doSomething,doSomethingElseWhenThatsDone,doYetAnotherThingWhenThatsDone)看起来像这样:

function doSomething(){
    //set up some JSOM stuff
    var dfd = $.Deferred();
    context.executeQueryAsync(
        function () {
            dfd.resolve();
        }, function (sender, args) {
            dfd.reject(sender, args, errorMsg);
        });
    return dfd.promise()
}
Run Code Online (Sandbox Code Playgroud)

每个都设置一个JQuery Deferred对象并返回它的Promise.Promise使调用函数等待,直到Promise被解析或拒绝(分别在ExecuteQueryAsync的成功或失败回调中).

你可以用承诺做更多的事情,这几乎没有表面上的痕迹.通常,它们允许您在必要时强制以同步方式执行异步调用.

HTH,

戴夫