javascript 如何让 ExecuteQueryAsync 的行为更同步?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22411220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:05:44  来源:igfitidea点击:

How do I get the ExecuteQueryAsync to behave more synchronously?

javascriptjquerysharepoint

提问by jazaddict

Aight..this Sharepoint using Javascript..I'm using Alerts to debug my Javascript that runs from a Content Editor Web Part; the script is in the Assets library .

Aight..this Sharepoint using Javascript..I'm using Alerts to debug my Javascript that running from a Content Editor Web Part; 该脚本位于资产库中。

I get it...the WHOLE POINT of "async" function calls is to not wait around for the call to finish....but I fear the actions in the ExecuteQueryAsync, upon which future actions rely, would not complete resulting in error.

我明白了......“异步”函数调用的全部要点是不要等待调用完成......但我担心 ExecuteQueryAsync 中的操作(未来操作所依赖的)不会完成导致错误.

I'm quite certain that, because of my Alert IN & Alert BACK firing "backwards" that i'm indeed getting my Asynchronous behaviour. I tried "ExecuteQuery" without the "Async" part...THAT failed miserably.

我很确定,因为我的 Alert IN 和 Alert BACK 向后发射,我确实得到了我的异步行为。我尝试了没有“异步”部分的“ExecuteQuery”......失败得很惨。

Somebody wanna gimme a shove in the right direction toward getting the activities in my ONSUCCESS function to finish before returning to the OBJ function?

有人想要在正确的方向上推动我的 ONSUCCESS 功能中的活动在返回到 OBJ 功能之前完成吗?

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*********     
}

回答by TimTheEnchanter

You want to look into Promises. Scot Hillier has an excellent write up here: http://www.shillier.com/archive/2013/03/04/using-promises-with-the-javascript-client-object-model-in-sharepoint-2013.aspxbut essentially they allow you to write code like this:

你想研究 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);

The functions you call to do your work (doSomething, doSomethingElseWhenThatsDone, doYetAnotherThingWhenThatsDone) would look something like this:

您调用来完成工作的函数(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()
}

Each sets up a JQuery Deferred object and returns it's Promise. The Promise causes the calling function to sit and wait until the Promise is either resolved or rejected (in the success or failure callbacks of ExecuteQueryAsync respectively).

每个设置一个 JQuery Deferred 对象并返回它的 Promise。Promise 导致调用函数坐下来等待 Promise 被解决或拒绝(分别在 ExecuteQueryAsync 的成功或失败回调中)。

You can do a lot more with promises, this barely scratches the surface. In general, they allow you to, when necessary, force async calls to be performed in a synchronous manner.

你可以用 Promise 做更多的事情,这只是触及表面。通常,它们允许您在必要时强制以同步方式执行异步调用。

HTH,

哈,

Dave

戴夫

回答by Erik Noren

This is expected behavior. The executeQueryAsynccall is non-blocking. That means it will pause there just long enough to get the query started before continuing with the rest of your code. You can register a success and a failure callback to handle the result of the query.

这是预期的行为。该executeQueryAsync调用是非阻塞的。这意味着它将在那里暂停足够长的时间以启动查询,然后再继续执行其余代码。您可以注册成功和失败回调来处理查询结果。

If you have code you want to execute after the query has completed, you should move it into those callbacks.

如果您有要在查询完成后执行的代码,则应将其移动到这些回调中。