不是作为jQuery Deferred执行的异步函数 [英] not asynchronous function executed as jQuery Deferred

查看:76
本文介绍了不是作为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]});
    });
});

执行它并表明进度:

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

问题是如果执行processWrongFileType,通知将无效。
如果我将processWrongFileType更改为如下所示:

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()将起作用。有没有办法避免使用setTimeout并仍然使用notify()处理进度事件?

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

推荐答案

你不需要做任何特别的事情为了使用同步代码作为承诺。

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

只返回值 == true

$.when((function() {
    return prompt('really?')
})()).then((function() { 
    return alert('yeah') 
})()).done((function () { 
    alert('done') 
})())

这篇关于不是作为jQuery Deferred执行的异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆