Jquery.deferred的语法,使同步函数返回promise [英] syntax for Jquery.deferred , making synchronous function return promise

查看:112
本文介绍了Jquery.deferred的语法,使同步函数返回promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于如何使用Jquery.deferred来生成慢速同步函数的快速问题会返回一个promise。
到目前为止我做的是:

A quick question on how to use Jquery.deferred to make a slow synchronous function return a promise instead. What I've done so far is this :

function sayIt(ms) {
    setTimeout( function() { console.log('what I say'); }, ms);
} 

function doIt() {
    return $.Deferred( function() { sayIt(2000); }).promise();
}


doIt().then( function() { console.log('ah'); });

sayIt(2000)总是通过,但'then'之后的链式函数永远不会触发。

the sayIt(2000) always goes through but the chained function after the 'then' never fires.

如果我这样做:

doIt().then( console.log('ah'));

'啊'马上出现,然后'我说'2000ms之后 - 什么我想要的当然是相反的 - 两秒后我得到'我说的'然后'啊'就在之后。

the 'ah' comes up right away, and then the 'what I say' 2000ms later - what I want is of course the opposite - that after two seconds I get 'what I say' and then 'ah' right after.

任何建议都值得赞赏!

推荐答案

要同步做某事但仍然使用承诺,请执行以下操作:

To do something synchronously, but still use a promise, do:

function slowPromise() {

    var def = $.Deferred();

    // do something slow and synchronous
    ...

    // resolve the deferred with the result of the slow process
    def.resolve(res);

    // and return the deferred
    return def.promise();
}

结果是你仍然得到了承诺,但是这个承诺已经解决了,所以任何 .then()随后立即在其上注册。

The effect is that you still get a promise, but that promise is already resolved, so any .then() which is subsequently registered on it proceeds immediately.

这种模式的优点是如果你随后用异步的东西替换同步代码,那么函数仍然具有相同的外部接口。

The advantage of this pattern is that if you subsequently replace the synchronous code with something asynchronous the function still has the same external interface.

这篇关于Jquery.deferred的语法,使同步函数返回promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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