如何使递延对象的数组 [英] How to make an array of Deferred objects

查看:295
本文介绍了如何使递延对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是新来Deferreds和承诺。

下面是我的[简体] code,这是一个JavaScript对象中定义的:

  myFunction的:功能(D,CB)
{
    返回$阿贾克斯('/ myURL',{
        的contentType:应用/ JSON,
        数据:D,
        数据类型:JSON,
        输入:POST
    }),然后(CB,CB);
},冲洗:功能(myarray的)
{
    返回myFunction的(myarray的,myCallBack函数);
}

以上工作正常。我可以调用flush(的someArray),一段时间后,我得到的Ajax请求的结果。

问:

我要修改的冲洗功能,使得它首先打破了阵列分成块(即小数组),然后在每块者来电myFunction的。那么它必须返回,一气呵成,在汇总的每个所做的AJAX调用。数据(preferably在一个阵列)

我开始大意如下修改的flush(),但我知道这是不完全正确。在间隙可以请别人完成/填写对我来说,还是建议重新构建,将工作呢?

感谢。

 刷新:功能(myarray的)
{
    变种块= 2;
    变种I,A;
    变种J = myArray.length;    变种myArrayChunks = [];    对于(i = 0; I<焦耳; I + =块)
    {
        A = myArray.slice(I,I +块);
        myArrayChunks.push(一);
    }    变种myDeferreds = [];    对于(i = 0; I< myArrayChunks.length;我++)
    {
        //在这里,我需要创建一个延迟对象,将运行:myFunction的(myArrayChunks [I],myCallBack函数)
        // 我怎么做?        变种F = //递延对象将运行:myFunction的(myArrayChunks [I],myCallBack函数)        myDeferreds.push(F);
    }    返回$ .when.apply($,myDeferreds)。然后(函数(){        //在这里,我需要得到由每个deferreds返回的汇总数据。我怎么做?        的console.log(FLUSH COMPLETE!);
    });
}


解决方案

感谢所有伟大的意见。

我用的建议技术的组合在我的解决方案。

最关键的事情就是做出承诺的数组,并推到它所需的电话(每个作为参数传递自己的数组块),以使Ajax请求的功能。有一件事我没有previously意识到的是,这要求在那一刻AjaxCall的()函数,这是很正常的,因为它返回一个推到阵列的承诺。

在此之后,when.apply'行的伎俩在等待,直到所有的AJAX履行诺言。在'然后'函数的参数是用来整理所有需要的结果(显然,对于其确切机制取决于你返回参数的格式)。然后将结果发送到theResultsHandler(),它在code原来的回调我第一次张贴在我的问题的地方。

希望这是其他承诺,新手非常有用!

AJAX的呼叫功能是:

 则AjaxCall:功能(D){
    返回$阿贾克斯('/ myURL',{
    的contentType:应用/ JSON,
    数据:D,
    数据类型:JSON,
    输入:POST
    });
},

和冲洗()函数中...

  VAR承诺= [];
    变种I,J;    对于(i = 0; I< batchChunks.length;我++)
    {
        promises.push(self.ajaxCall(batchChunks [I]));
    }    变种结果= [];    返回$ .when.apply($,承诺)。然后(函数(){        的console.log(论据=+ JSON.stringify(参数));        对于(i = 0; I<与arguments.length;我++)
        {
            为(J = 0; J&下;参数[I] [0]。长度; J ++)
            {
                results.push(参数[I] [0] [J]);
            }
        }        返回self.theResultsHandler(结果);
    });

Am new to Deferreds and Promises.

Here is my [simplified] code, which is defined within a JavaScript object:

myFunction: function(d, cb)
{
    return $.ajax('/myURL', {
        contentType:    'application/json',
        data:           d,
        dataType:       'json',
        type:           'POST'
    }).then(cb, cb);
},

flush: function(myArray)
{
    return myFunction(myArray, myCallback);
}

The above works fine. I can call flush(someArray), and some time later I get the result of the ajax request.

QUESTION:

I want to modify the flush function so that it first breaks the array into chunks (i.e. smaller arrays), and then calls myFunction on each of those chunks. It must then return, in one go, the aggregated data (preferably in an array) from each of the ajax calls that were made.

I am starting to modify flush() along the following lines, but I know it's not quite right. Please can someone complete/fill in the gaps for me, or suggest a re-structuring that would work well?

Thanks.

flush: function(myArray)
{
    var chunk = 2;
    var i, a;
    var j = myArray.length;

    var myArrayChunks = [];

    for (i=0; i<j; i+=chunk)
    {
        a = myArray.slice(i, i+chunk);
        myArrayChunks.push(a);
    }

    var myDeferreds = [];

    for (i=0; i<myArrayChunks.length; i++)
    {
        // Here, I need to create a deferred object that will run: myFunction(myArrayChunks[i], myCallback)
        // How do I do that?

        var f = // The deferred object that will run: myFunction(myArrayChunks[i], myCallback)

        myDeferreds.push(f);
    }   

    return $.when.apply($, myDeferreds).then(function(){

        // Here, I need to get the aggregated data that is returned by each of the deferreds. How do I do that?

        console.log("FLUSH COMPLETE!");
    }); 
}

解决方案

Thanks to all for great advice.

I used a combination of the suggested techniques in my solution.

The key thing was to make an array of promises, and push onto it the required calls (each with its own array chunk passed as a parameter) to the function that makes the ajax request. One thing I hadn't previously realised is that this calls the ajaxCall() function at that very moment, and that's ok because it returns a promise that is pushed onto the array.

After this, the 'when.apply' line does the trick in waiting until all the ajax promises are fulfilled. The arguments of the 'then' function are used to collate all the results required (obviously, the exact mechanism for that depends on the format of your returned arguments). The results are then sent to theResultsHandler(), which takes the place of the original callback in the code I first posted in my question.

Hope this is useful to other Promise-novices!

The ajax-calling function is:

ajaxCall: function(d) {
    return $.ajax('/myURL', {
    contentType:    'application/json',
    data:           d,
    dataType:       'json',
    type:           'POST'
    });
},

And inside the flush() function...

    var promises = [];
    var i, j;

    for (i=0; i<batchChunks.length; i++)
    {
        promises.push(self.ajaxCall(batchChunks[i]));
    }   

    var results = [];

    return $.when.apply($, promises).then(function(){

        console.log("arguments = " + JSON.stringify(arguments));

        for (i = 0; i < arguments.length; i++)
        {
            for (j = 0; j < arguments[i][0].length; j++)
            {
                results.push(arguments[i][0][j]);
            }
        }

        return self.theResultsHandler(results);
    }); 

这篇关于如何使递延对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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