GibboK
GibboK

Reputation: 73908

How can I sequence asynchronous operations using jQuery?

I am using jQuery v2.1.4, I have the following function which for each object in evt.data.files(the number of element in the array will vary) needs to make a request to a server.

The problem I am facing with this script is that for each element in evt.data.files an asynchronous request is made, instead I need:

Could you please suggest me a solution with an example? Thanks.

options.onInit = function (finder) {
    finder.on('files:choose', function (evt) {
        // files is an array of n object
        evt.data.files.forEach(function (file) {
            // req is an jquery deferred object
            var req = finder.request('command:send', {
                name: 'ImageInfo',
                folder: file.get('folder'),
                params: { fileName: file.get('name') }
            }).done(function (response) {
                if (response.error) {
                    return;
                }

            });
        });
    });
}.bind(this);

Upvotes: 0

Views: 328

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

I realise I misread the question first time. You only need to run the requests sequentially and await the last one:

Use promise = promise.then(newPromise) to chain promises sequentially:

e.g.

options.onInit = function (finder) {
    finder.on('files:choose', function (evt) {
        var promise = $.when(); // start with a resolved promise

        // files is an array of n object
        evt.data.files.forEach(function (file) {
            promise = promise.then(function(){
               return finder.request('command:send', {
                  name: 'ImageInfo',
                  folder: file.get('folder'),
                  params: { fileName: file.get('name') }
               });
            });
        });
        promise.then(function(){
            alert("Last one done");
        });
    });
}.bind(this);

The key feature here is to return the promise inside an anonymous function in each then call. This defers the execution until the previous promise resolves, but still chains the promises.

Upvotes: 2

Related Questions