在Windows Azure中同步的请求? [英] Synchronous request in Windows Azure?

查看:145
本文介绍了在Windows Azure中同步的请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在我的服务器code,变量邀请是成功的功能外不确定

 函数getInvites(ID){
    VAR InvitesTable = tables.getTable(请),其中({PlanID:ID})。选择(用户名,主治);
    VAR邀请;
    InvitesTable.read({成功:函数(resultss){
                           邀请= resultss;
                           的console.log(邀请); //在这里工作
                           }});
    的console.log(邀请); //此处未定义
}

从类似的问题,我知道,因为它是异步的,它的。因此,成功的函数调用的的console.log(邀请)后运行; //此处未定义电话。

我的问题是我如何停止在Windows Azure中?

加code

 函数read(查询,用户要求){        request.execute({
            成功:函数(结果){
                results.forEach(函数(R){                    getInvites(r.id,功能(邀请){
                        r.invites =邀请;
                    });
                });
                request.respond();
            }
        });}功能getInvites(ID,CB){
    VAR InvitesTable = tables.getTable(请),其中({PlanID:ID})。选择(用户名,主治);
    InvitesTable.read({成功:函数(结果){
                           如果(CB)CB(结果);
                           }});
}


解决方案

您没有停止,你设计你身边正在使用的任何环境的本质异步您的应用程序。

我假设你正在试图做这样的事情:

 函数getInvites(ID){
    VAR InvitesTable = tables.getTable(请),其中({PlanID:ID})。选择(用户名,主治);
    VAR邀请;
    InvitesTable.read({成功:函数(resultss){
                           邀请= resultss;
                           }});
    返回邀请;
}//后...VAR邀请= getInvites(someId);
//做一些与`invites`

这显然是行不通的,因为你返回邀请的价值异步调用完成之前。

相反,你写你的应用程序在异步方式:

 函数getInvites(ID,CB){
    VAR InvitesTable = tables.getTable(请),其中({PlanID:ID})。选择(用户名,主治);
    InvitesTable.read({成功:函数(resultss){
                           如果(CB)CB(resultss);
                           }});
}//后...getInvites(someId,功能(邀请){
    //做一些与`invites`
});

这省去了错误处理code为简单起见,所以你必须要补充一点为好。


看到你的全code后,它看起来像你必须管理大量并行异步操作的一个简单的问题。考虑会发生什么:你的循环运行,迭代的 N 的对象的数组。对于每一个,你叫 getInvites ,其中开始的数据库请求并返回。

这意味着你的循环运行速度很快,但现在你必须的 N 的杰出数据库请求,你必须等待你可以叫 request.respond()

这是的非常的基本的解决办法是做这样的事情算你的 getInvites 回调被调用的次数,最后完成请求当数量达到的 N

然而,这是费时又容易出错来管理这个手工记账每次进​​行异步请求的时间。这是流量控制库是非常有用的情况。我将使用jQuery的 递延 在这个例子中,因为它可能已经很熟悉(即使你不知道你实际上已经与之前使用的MDASH它;如果你曾经使用jQuery的API XHR,你使用递延 S)。

既然你在服务器环境中的时候,你显然不具备的jQuery;然而,还有谁只提取了$ C $必要℃,延迟为您

一旦我们有了递延 S代表每一个悬而未决的要求,我们可以使用的 来注册,获取唯一的所有的挂起递延之后调用回调氏完全。

 函数read(查询,用户要求){        request.execute({
            成功:函数(结果){
                VAR DFDS = [];
                对于(VAR I = 0; I< results.length;我++){
                    dfds.push(getInvites(结果[I] .ID)); //使Deferreds重新presenting数组
                                                          //我们每一个未决请求。
                }
                Deferred.when.apply(递延,DFDS)//详见下文
                    .done(函数(){
                        对于(VAR I = 0; I< results.length;我++){
                            结果[I] .invites =参数[I] //每一组的邀请复制到每个结果
                        }
                        request.respond(); //我们就大功告成了!
                    })
                    .fail(函数(){
                        //这里处理错误
                    });
            }
        });}功能getInvites(ID){
    VAR DFD =新递延(); //创建一个新的推迟,这在待定状态将自动启动
    VAR InvitesTable = tables.getTable(请),其中({PlanID:ID})。选择(用户名,主治);
    InvitesTable.read({成功:函数(结果){
                           dfd.resolve(结果); //当我们找回数据,我们的决心的推迟 -
                                                 //换句话说,说其操作完成,
                                                 //并沿操作结果通过。
                           },
                        错误:功能(错误){// TODO:不知道这是你如何使用手柄错误API
                            dfd.reject(ERR); //标志着递延为失败。
                        }});    返回dfd.promise(); //我们(同步)返回的承诺。来电者可以附加事件处理程序
                          //应许,当我们最终解决或拒绝递延对其调用。
}

注:


  • jQuery.when (或在此服务器端的情况下, Deferred.when )通常希望你通过递延 s的固定数量的参数:

      $时(dfd1,dfd2).done(功能(RESULT1,结果2){...});

    但是,我们有一个可变数目递延取值,所以我们必须的 适用 递延阵列 s到,然后在完成处理程序,通过隐式访问每个结果<一个href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments\"相对=nofollow> 参数 对象。


  • Array.forEach(...)。在大多数情况下,最好是使用常规的循环。


So in my server code, variable invites is undefined outside of the success function.

function getInvites(id){
    var InvitesTable = tables.getTable("Invites").where({"PlanID": id}).select("UserID","Attending");
    var invites;
    InvitesTable.read({ success: function(resultss) { 
                           invites = resultss;
                           console.log(invites); //works here
                           }});
    console.log(invites); //undefined here
}

From similar questions, I realize its because of it being asynchronous. So the success function call is run after the console.log(invites); //undefined here call.

My question is how do I stop that in Windows Azure?

Added code

function read(query, user, request) {

        request.execute({
            success: function(results) {
                results.forEach(function(r) {

                    getInvites(r.id, function(invites) {
                        r.invites = invites;
                    });
                });
                request.respond();
            }
        });

}

function getInvites(id, cb){
    var InvitesTable = tables.getTable("Invites").where({"PlanID": id}).select("UserID","Attending");
    InvitesTable.read({ success: function(results) {
                           if (cb) cb(results);
                           }});
}

解决方案

You don't "stop that," you design your application around the async nature of whatever environment you're using.

I assume you're trying to do something like this:

function getInvites(id){
    var InvitesTable = tables.getTable("Invites").where({"PlanID": id}).select("UserID","Attending");
    var invites;
    InvitesTable.read({ success: function(resultss) { 
                           invites = resultss;
                           }});
    return invites;
}

// later...

var invites = getInvites(someId);
//do something with `invites`

This obviously won't work, since you return the value of invites before the async call completes.

Instead, you write your app in async style:

function getInvites(id, cb){
    var InvitesTable = tables.getTable("Invites").where({"PlanID": id}).select("UserID","Attending");
    InvitesTable.read({ success: function(resultss) { 
                           if (cb) cb(resultss);
                           }});
}

// later...

getInvites(someId, function(invites) {
    //do something with `invites`
});

This leaves out error handling code for the sake of simplicity, so you'd have to add that as well.


After seeing your full code, it looks like you have a simple problem of managing many parallel asynchronous operations. Consider what happens: your loop runs, iterating over an array of n objects. For each, you call getInvites, which begins a database request and returns.

This means your loop runs very quickly, but now you have n outstanding database requests that you must wait on before you can call request.respond().

An extremely basic solution would be to do something like count the number of times your getInvites callback is called, and then finally complete the request when that number reaches n.

However, it is time-consuming and mistake-prone to manage this bookkeeping manually every time you make async requests. This is a situation where flow control libraries are extremely useful. I will use jQuery's Deferred in this example, since it may already be familiar to you (even if you don't know you've actually used it before — if you've ever used jQuery's XHR API, you've used Deferreds).

Given that you're in a server environment, you obviously don't have jQuery; however, there are people who have extracted only the code necessary for Deferred for you.

Once we have Deferreds for every pending request, we can use when to register a callback that gets called only after all pending Deferreds complete.

function read(query, user, request) {

        request.execute({
            success: function(results) {
                var dfds = [];
                for (var i = 0; i < results.length; i++) {
                    dfds.push(getInvites(results[i].id)); // Makes an array of Deferreds representing
                                                          // each of our pending requests.
                }


                Deferred.when.apply(Deferred, dfds) // see details below
                    .done(function() {
                        for (var i = 0; i < results.length; i++) {
                            results[i].invites = arguments[i]; // Copy each set of invites to each result
                        }
                        request.respond(); // We're done!
                    })
                    .fail(function() {
                        // Handle errors here
                    });
            }
        });

}

function getInvites(id){
    var dfd = new Deferred(); // Create a new Deferred, which automatically starts in the 'pending' state
    var InvitesTable = tables.getTable("Invites").where({"PlanID": id}).select("UserID","Attending");
    InvitesTable.read({ success: function(results) {
                           dfd.resolve(results); // When we get data back, we 'resolve' the Deferred --
                                                 // in other words, say its operation is done,
                                                 // and pass along the operation's results.
                           },
                        error: function(err) { // TODO: Not sure if this is how the API you're using handles errors
                            dfd.reject(err); // Marks the Deferred as failed.
                        }});

    return dfd.promise(); // We (synchronously) return the Promise.  The caller can attach event handlers
                          // to the Promise, which are invoked when we eventually resolve or reject the Deferred.
}

Notes:

  • jQuery.when (or in this server-side case, Deferred.when) normally expects you to pass a fixed number of Deferreds as arguments:

    $.when(dfd1, dfd2).done(function(result1, result2) { ... });
    

    However, we have a variable number of Deferreds, so we must apply an array of Deferreds to when and then in the done handler, access each result via the implicit arguments object.

  • Array.forEach(...) is slow. In most cases, it is better to use a regular for loop.

这篇关于在Windows Azure中同步的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆