Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not asynchronous function executed as jQuery Deferred

Lets say I want to process some tasks in the synchronous manner, so I have this function:

function executePromiseQueueSync(queue){
    var seed = $.Deferred(),
        finalPromise;

    finalPromise = _.reduce(queue, function(memo, promise){
        return memo.then(function(){
            return promise.funct.apply(null, promise.argmnt);
        });
    }, seed.promise());

    seed.resolve();
    return finalPromise;
}

Now I can use it to process some files:

_.each(fileList, function(element, index, list){
    _.each(element, function(el, idx, lst){
        promisesQueue.push({funct: processFile, argmnt:[el, index + (len - fileList.length) ,len]});
    });
});

Execute it and indicate a progress:

executePromiseQueueSync(promisesQueue).then(function(){
   ....
}, function(){
    ....
}).progress(function(msg, progress, name, index, status, desc){
        console.log('progress');
});

Process function itself looks like this:

function processFile(file, index, size)
{
    var dfd = new jQuery.Deferred();
    if (file.name.match('(.*)\\.jpg'))
        ...
    else if
        ...
    else
       $.when(processWrongFileType(file)).then(function(){
         dfd.notify(...);
         dfd.resolve();
      });

    return dfd.promise();
}

as you see there is nothing much to do when the file has a wrong type:

So sometimes I would like to execute synchronous code just like a promise:

function processWrongFileType(){
    var dfd = new jQuery.Deferred();
    dfd.resolve();
    console.log("blah");
    return dfd.promise();
}

The problem is if processWrongFileType will be executed, notify will not work. If I change processWrongFileType to look like this:

function processWrongFileType()
{
    var dfd = new jQuery.Deferred();
    setTimeout(function(){dfd.resolve();},1);
    return dfd.promise();
}

notify() will work. Is there any way to avoid setTimeout and still have notify() working with progress event?

like image 460
mnowotka Avatar asked Apr 05 '13 15:04

mnowotka


People also ask

What is Deferred () in jQuery?

Deferred() A factory function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

Is jQuery function asynchronous?

The jQuery Ajax async is handling Asynchronous HTTP requests in the element. It is a procedure to send a request to the server without interruption. It is an Asynchronous method to send HTTP requests without waiting response. It is a function to working on a server without associating more than on request.

How use jQuery Deferred and promise?

promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists. If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point.

Is jQuery synchronous?

By default jQuery is not providing synchronous request, so we have to implicitly define synchronous request using $. ajax(). In the above code you can observe we are declaring false for the async parameter.


1 Answers

You dont need to do anything special in order to use sync code as promise.

Just return value that is ==true

$.when((function() {
    return prompt('really?')
})()).then((function() { 
    return alert('yeah') 
})()).done((function () { 
    alert('done') 
})())
like image 167
vittore Avatar answered Oct 18 '22 09:10

vittore