生成AJAX请求动态基于场景 [英] Generating AJAX Request Dynamically Based on Scenario

查看:179
本文介绍了生成AJAX请求动态基于场景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单地说,我试图动态生成基于关闭,我通过从服务器AJAX请求正在检索场景AJAX请求。

的想法是,

  1. 在一台服务器提供了一个方案对我来说,生成一个Ajax请求。
  2. 在我生成基于​​关闭方案一个Ajax请求。
  3. 然后我在循环中重复这个过程,一遍又一遍。

最大的想法是,我可以动态改变第二个AJAX请求,根据关从服务器给出的情景。

我有这个工作,但我觉得我做的这是非常混乱的方式。有没有更好的办法去了解过这个问题的思考?也许承诺?如果任何人都可以请参阅本,并提供反馈或就如何把它清理干净的建议 - 这将是极大的AP preciated

下面是我的code: http://jsfiddle.net/6jph0e98/ (请打开控制台看到的一切行动)

作为参考,在这里是这种情况下的数据我目前正在使用:

  VAR场景= {
        基础: {
            频率:5000
        },
        端点:[
            {
                方法:GET,
                类型:JSON,
                终点:https://api.github.com/users/alvarengarichard
                queryParams:{
                    目标:目的1,objective2,objective3
                }
            }
        ]
    }
 

解决方案

下面是我的2美分: HTTP:/ /jsfiddle.net/3Lddzp9j/6/

是的,我想你可以通过链接承诺做到这一点更优雅。因此,我想通了,我觉得你的应用程序做,以及如何通过链接这些承诺做到这一点。有趣的是,某些步骤已经返回承诺(jQuery的AJAX调用),但另一些则不然。对于那些 - 我们必须创建自己的承诺,立即解决。再有,我们包裹在一个承诺超时。

另外,我试图用一些JS的最佳做法,如通过包装他们在一个的生活to 和应用的模块模式。 这使得你的应用程序非常干净恕我直言的整体控制流程:

 变种运行=函数(){
        getScenario()
        。然后(mapToInstruction)
        。然后(waitForTimeout)
        。然后(callApi)
        。然后(handleResults)
        。然后(运行);
    };
 

和还隐藏了私有成员,只有公开run()方法:

 返回{
        //这将只暴露的run方法
        //并保持所有其他职能的私人
        跑跑
    }
 

希望它帮助 - 让我知道你在想什么。下面是完整的源代码,有注释:

  //首先 - 我在这里使用的JavaScript模块模式
//这都将是更容易,一旦ES6出来,但这样会
//需要做的现在。
//另外,我进口的jQuery到模块中,你可以看到,这
//被包裹的生活to内(谷歌它),这让事情很好
//了全球范围。
VAR应用=(函数($){

    //获取来自API的情况下 -  $不用彷徨只是一些句法
    //糖$就用GET作为方法 - 注:此方法返回一个承诺
    VAR getScenario =功能(){
        的console.log('获得的场景......);
        返回$获得('http://demo3858327.mockable.io/scenario');
    };

    //的previous承诺,结果被传递到
    //接下来,我们正在链接。所以数据将包含
    // getScenario结果
    VAR mapToInstruction =功能(数据){
        //我们将其映射到一个新的指令对象
        VAR指令= {
            方法:data.endpoints [0]。方法,
            类型:data.endpoints [0] .TYPE,
            终点:data.endpoints [0] .endPoint,
            频率:data.base.frequency
        };

        的console.log('说明:收到:);
        执行console.log(指令);

        //现在我们创建这个承诺
        //指令,以便我们能够IT连锁
        VAR推迟= $ .Deferred();
        deferred.resolve(指令);
        返回deferred.promise();
    };

    //这个包装了的setTimeout成一个承诺,再次
    //所以我们可以IT连锁
    VAR waitForTimeout =函数(指令){
        的console.log('等待'+ instruction.frequency +MS);
        VAR推迟= $ .Deferred();
        的setTimeout(函数(){
            deferred.resolve(指令)
        },instruction.frequency);
        返回deferred.promise();
    };

    //最后一步:调用从该API
    //提供的说明
    VAR callApi =函数(指令){
        的console.log(API调用给定的指令......');
        返回$阿贾克斯({
            类型:instruction.method,
            数据类型:instruction.type,
            网址:instruction.endpoint
        });
    };

    VAR handleResults =功能(数据){
        的console.log(处理数据......);
        VAR推迟= $ .Deferred();
        deferred.resolve();
        返回deferred.promise();
    };

    //在'运行'的方法
    变种运行=函数(){
        getScenario()
        。然后(mapToInstruction)
        。然后(waitForTimeout)
        。然后(callApi)
        。然后(handleResults)
        。然后(运行);
    };

    返回 {
        //这将只暴露的run方法
        //并保持所有其他职能的私人
        跑跑
    }
})($);

// ...并启动应用程序
App.run();
 

Simply put, I'm trying to dynamically generate an AJAX request based off a scenario that I'm retrieving via an AJAX request from a server.

The idea is that:

  1. A server provides a "Scenario" for me to generate an AJAX Request.
  2. I generate an AJAX Request based off the Scenario.
  3. I then repeat this process, over and over in a Loop.

The big idea is that I can change the second AJAX request dynamically, based off the Scenario given from the server.

I have this working, but I feel like the way I'm doing this is very messy. Is there any better way to go about thinking through this problem? Perhaps promises? If anyone could please review this and provide feedback or suggestions on how to clean it up--that would be greatly appreciated.

Here is my code: http://jsfiddle.net/6jph0e98/ (please open the console to see everything in action)

As a reference, here is the scenario data I'm currently working with:

    var scenario = {
        "base": {
            "frequency": "5000"
        },
        "endpoints": [
            {
                "method": "GET",
                "type": "JSON",
                "endPoint": "https://api.github.com/users/alvarengarichard",
                "queryParams": {
                    "objectives": "objective1, objective2, objective3"
                }
            }
        ]
    }

解决方案

Here are my 2 cents: http://jsfiddle.net/3Lddzp9j/6/.

Yes, I think you can do this more elegantly by chaining promises. So I figured out what I think your app does, and how you can do it by chaining these promises. What is interesting that certain steps already return promises ( the jQuery AJAX calls ) but others don't. For those - we have to create our own promise that instantly resolves. And then there was the timeout which we wrapped in a promise.

Also, I tried to use some JS best practices, like keeping things out of the global space by wrapping them in an IIFE and applying the module pattern. This makes the overall control flow of your application nice and clean IMHO:

    var run = function() {
        getScenario()
        .then(mapToInstruction)
        .then(waitForTimeout)
        .then(callApi)
        .then(handleResults)
        .then(run);
    };

And also hides the private members and only exposes the run() method:

    return {
        // This will expose only the run method
        // and will keep all other functions private
        run : run
    }

Hope it helps - let me know what you think. Here's the full source, with comments:

// First of all - I'm using the javascript module pattern here
// this will all be much more easy once ES6 it out, but this will
// have to do for now.
// Also, I'm importing jQuery into the module as you can see, which
// is wrapped inside the IIFE ( Google it ) which keeps things nicely
// out of the global scope.
var App = (function ($) {

    // Gets the scenario from the API - $.get is just some syntactic
    // sugar for $.ajax with GET as method - NOTE: this returns a promise
    var getScenario = function () {
        console.log('Getting scenario ...');
        return $.get('http://demo3858327.mockable.io/scenario');
    };

    // The result of the previous promise is passed into the 
    // next as we're chaining. So the data will contain the 
    // result of getScenario
    var mapToInstruction = function (data) {
        // We map it onto a new instruction object
        var instruction = {
            method: data.endpoints[0].method,
            type: data.endpoints[0].type,
            endpoint: data.endpoints[0].endPoint,
            frequency: data.base.frequency
        };

        console.log('Instructions recieved:');
        console.log(instruction);

        // And now we create a promise from this
        // instruction so we can chain it
        var deferred = $.Deferred();
        deferred.resolve(instruction);
        return deferred.promise();
    };

    // This wraps the setTimeout into a promise, again
    // so we can chain it
    var waitForTimeout = function(instruction) {
        console.log('Waiting for ' + instruction.frequency + ' ms');
        var deferred = $.Deferred();
        setTimeout(function() {
            deferred.resolve(instruction)
        }, instruction.frequency); 
        return deferred.promise();
    };

    // Final step: call the API from the 
    // provided instructions
    var callApi = function(instruction) {
        console.log('Calling API with given instructions ...');
        return $.ajax({
            type: instruction.method,
            dataType: instruction.type,
            url: instruction.endpoint
        });
    };

    var handleResults = function(data) {
        console.log("Handling data ...");
        var deferred = $.Deferred();
        deferred.resolve();
        return deferred.promise();
    };

    // The 'run' method
    var run = function() {
        getScenario()
        .then(mapToInstruction)
        .then(waitForTimeout)
        .then(callApi)
        .then(handleResults)
        .then(run);
    };

    return {
        // This will expose only the run method
        // and will keep all other functions private
        run : run
    }
})($);

// ... And start the app
App.run();

这篇关于生成AJAX请求动态基于场景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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