not asynchronous function executed as jQuery Defer

2019-04-04 14:05发布

问题:

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?

回答1:

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') 
})())