简体   繁体   English

如何使用promises为对象数组的每个元素进行ajax调用?

[英]How to make an ajax call for each element of an array of objects, using promises?

I have this code: 我有这个代码:

       // _arrOfUsers = array of objects, each object represents a user. 
       //For example, a single object may be something like {name:"mike", id:"123"}    

            var _successUsers = function (_arrOfUsers) {            
                    var promises = [];   //empty array of promises

                        _arrOfUsers.forEach(function (user) {
                            promises.push(function () {
                                return $.Deferred(function (dfd) {
                                     $.post("//sessionID",
                                                queryServ.getAllUserDomainCommentsFunc("//currentDomainID", user.iD, "//currentDomainID", "//currentURL"),
                                        'text', 'text/plain', this,
                                        function (dataX) {
                                            dfd.resolve(dataX);
                                        });
                                }).promise();
                            });
                    });

                    $.when(promises).then(function (results) {
                        console.log(results);
                    });

                };

Some elements to understand this code: 了解此代码的一些元素:

**** Ajax call settings **** Ajax通话设置

  • url: sessionURL url:sessionURL
  • data: data to send to the server is an external call to the module queryServ.js and the function getAllUserDomainCommentsFunct that returns a JSON object. data:要发送到服务器的数据是对模块queryServ.js的外部调用以及返回JSON对象的函数getAllUserDomainCommentsFunct。 It needs these parameters to work: currentDomain, userID, currentDomain (again), currentURL 它需要这些参数:currentDomain,userID,currentDomain(再次),currentURL
  • type: text 类型:文字
  • contentType: text/plain contentType:text / plain
  • context: this 上下文:这个

**** A comment is a jsonObject smilar to {id: "998", textOfcomment:"I commented this", target: "//targetID"}. ****注释是jsonObject smilar到{id: "998", textOfcomment:"I commented this", target: "//targetID"}.

What I want to do is to make an ajax call for each user of the array "_arrOfUsers" to extract all his comments on the server; 我想要做的是为数组“_arrOfUsers”的每个用户进行ajax调用,以便在服务器上提取他的所有注释; after all the "extractions" I need to get all the results (that are all the comments from all users) and print them in the console. 在所有“提取”之后,我需要获得所有结果(这是所有用户的所有注释)并在控制台中打印它们。 The order is important for my code, this is why I'm using Promises. 顺序对我的代码很重要,这就是我使用Promises的原因。

I found the structure of this algorithm on a JSfiddle here on StackOverflow, but it doesn't work for me because it returns an array of functions and I can't understand why, probably because I've never used Promises during my career. 我在StackOverflow上的JSfiddle上找到了这个算法的结构,但它对我不起作用,因为它返回一个函数数组,我无法理解为什么,可能是因为我在职业生涯中从未使用过Promises。

Thank you in advance, if there's something not clear please feel free to tell me. 提前谢谢,如果有不清楚的地方请随时告诉我。

There's no need to create a deferred here since $.post() already returns a promise and $.when() keeps the results in order for you. 由于$.post()已经返回一个promise而$.when()按顺序保存结果,因此无需在此处创建延迟。 Instead, you can do this: 相反,你可以这样做:

$.when.apply($, _arrOfUsers.map(function(user) {
    return $.post("//sessionID", queryServ.getAllUserDomainCommentsFunc("//currentDomainID", user.iD, "//currentDomainID", "//currentURL"));
})).then(function() {
    // all results available in order here as arguments to this callback
    // arguments[0][0] is the first result
    // arguments[1][0] is the second result
    // arguments[2][0] is the third result and so on 
    for (var i = 0; i < arguments.length; i++) {
        // arguments[i][0] is next one  of your results
    }
});

Note: I didn't quite understand what you were trying to do with the arguments to $.post() (you seem to have made up some arguments the jQuery doc doesn't show) so I simplified it somewhat, but you may need to tweak those $.post() arguments to suit your purpose. 注意:我不太明白你试图用$.post()的参数做什么(你好像已经$.post()了jQuery doc没有显示的一些参数)所以我稍微简化了一下,但你可能需要调整那些$.post()参数以满足您的目的。


Personally, I despise $.when() and how it interacts with jQuery ajax promises (very confusing to use) so I would cast the ajax promise to an ES6 promise and use Promise.all() (using Bluebird for promise support if older browser support is needed). 就个人而言,我鄙视$.when()以及它如何与jQuery ajax promises交互(非常混淆使用)所以我会将ajax承诺转换为ES6承诺并使用Promise.all() (如果旧浏览器使用Bluebird进行承诺支持)需要支持)。

Promise.all(_arrOfUsers.map(function(user) {
    return Promise.resolve($.post("//sessionID", queryServ.getAllUserDomainCommentsFunc("//currentDomainID", user.iD, "//currentDomainID", "//currentURL")));
})).then(function(results) {
    // results is an array of results in order
});

Or if you include Bluebird, you can use: 或者,如果您包含Bluebird,您可以使用:

Promise.map(_arrOfUsers, function(user) {
    return Promise.resolve($.post("//sessionID", queryServ.getAllUserDomainCommentsFunc("//currentDomainID", user.iD, "//currentDomainID", "//currentURL")));
}).then(function(results) {
    // results is an array of results in order
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 for 循环中的 AJAX 问题:如何对数组的每个元素进行 ajax 调用? - Problem with AJAX in a for loop : How can i make an ajax call on each element of an array? 如何使用reduce和promises等待数组中每个元素的AsyncRequests - How to wait for AsyncRequests for each element from an array using reduce and promises 使用延迟的对象/诺言的Ajax调用返回失败 - Ajax call return fail using deferred objects / promises 如何从ajax调用的php响应中制作数组的jquery对象 - How to make jquery objects of array from php response of ajax call 如何在对象数组上异步查询 API,然后正确改变每个对象? (正确使用承诺) - How do I asynchronously query an API on an array of objects and then mutate each object correctly? (Using promises correctly) 使用Promise将元素推入数组 - Pushing an Element into an Array Using Promises 如何进行多个承诺调用 - How to make multiple promises call 如何使用ajax调用进行选择。检索时会生成一个数组 - how to make a select option using ajax call .on retrieval it produces an array 剔除使用ajax调用中的数据更新可观察数组的每个元素的属性 - knockout updating the property of observable array's each element using data from an ajax call 如何对HTML元素进行AJAX调用? - How to make an AJAX call to an html element?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM