Sandrooco Sandrooco - 1 year ago 81
jQuery Question

What's the best way to loop through ajax calls

I'm working with Sharepoint and I have an app that creates lists in the site collection (not the app!). Creating the list isn't a problem.
I wan't to create 15 columns and add them to the default view. I prepared a "config" with the information for the list and its fields.

var ChangeRequestLogListConfig = {
listName: 'ChangeRequestLog',
fields: [
{ 'FieldTypeKind': 8, 'Title': 'STC Relevant', 'InternalName': 'STCrelevant', 'StaticName': 'STCrelevant' },
{ 'FieldTypeKind': 3, 'Title': 'Description/Reason', 'InternalName': 'DescriptionReason', 'StaticName': 'DescriptionReason' },
{ 'FieldTypeKind': 6, 'Title': 'Source of Change', 'InternalName': 'SourceOfChange', 'StaticName': 'SourceOfChange', 'Choices': { 'results': ['customer', 'internal'] } },
//12 more objects like the above

There we come to the problem: with the rest resources
(with http post to create new ones) only support one parameter which means I have to do 2x15 ajax calls.

What's the proper approach to doing all these 30 operations and then do a final callback? Of course I know how to loop through the array of fields, I simply have no clue how to build that final callback the proper way.

Update / Follow-up

With the help of a few answers I managed to build the following code:

var spExecutor = new SP.RequestExecutor(_spPageContextInfo.siteAbsoluteUrl);
var requestUrl = _spPageContextInfo.siteAbsoluteUrl + "/_api/SP.AppContextSite(@target)/web/Lists/getbytitle('" + listConfig.listName + "')/fields?@target='" + hostWebUrl + "'";

//map field configs to promises
var promises = => {
return spExecutor.executeAsync({
url: requestUrl,
method: "POST",
body: JSON.stringify(fieldConfig),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose"
error: err => console.log(err)

//Wait for all calls to be done
$.when.apply($, promises).then(callbackFn);

As you probably already saw, I'm not using
but the
The problem: This doesn't return promises the same way as jQuery's ajax. This results in timing problems (--> 15 Calls at once, browsers mostly only support 4 parallel calls). The code above works, if I set a breakpoint and wait 1-2 seconds between the calls it creates all fields as expected.

My follow-up question: How can I wait for the completion of the first call to init the second, then the third and so on?
I'm not sure if I'm using the promises the right way.

Answer Source

Use .map to convert each field into a Promise:

var promises =
    item => $.ajax( ... )

and then $.when to wait for them all to complete:

$.when.apply($, promises).then( ... );

Note that this will start as many AJAX requests in parallel as your browser will permit - typically four.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download