魔术JQuery的递延与一元符 [英] Conjuring JQuery Deferred with monadic incantations

查看:116
本文介绍了魔术JQuery的递延与一元符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个(优秀)讨论=HTTP ://jsfiddle.net/Benjol/XNbXF/相对=nofollow>全球存储'code

Inspired by this (excellent) discussion of using Promises in javascript, I'm trying to work out how I could use Deferred to chain together async and non-async functions, to avoid paying the callback tax when using my 'Global storage' code.

我已经得到了与此相关的几个问题,但我会问他们聚集在这里,因为上下文是一样的。

I've got a few questions related to this, but I'll ask them together here, because the context is the same.

有一件事我不能工作是我怎样才能使一个延期出来的东西,是不是异步的 - 那就是,我怎么取一个值,承诺纸包起来,然后直接返回呢? ( A - > M< A>

One thing I can't work out is how I can make a deferred out of something that isn't asynchronous - that is, how do I take a value, wrap it in a promise, and return it directly? (a -> M<a>)

另外,我怎么可以采取异步函数,因此它直接返回其结果包裹,但包裹在一个承诺? ((A - &GT; B) - &GT;(一 - &GT; M&LT; B&GT;)

Also, how can I take an asynchronous function and wrap it so that it returns its result directly, but wrapped in a promise? ((a -> b) -> (a -> M<b>))

最后一个问题,对于一元怪胎 - 是有这个功能的标准名称? [A] - &GT; (一 - &GT; M&LT; B&GT;) - GT; M&LT; [B]&GT;

Last question, for monadic freaks - is there a standard name for this function? [a] -> (a -> M<b>) -> M<[b]>

推荐答案

结束语一个值的承诺是使用$。当简单的:

Wrapping a value into a promise is as simple as using $.when:

var promise = $.when( value );

另外,在jQuery 1.6的,你有一个非常简单的链接方法(管道):

Also, as of jQuery 1.6, you have a very simple chaining method (pipe):

var chained = functionThatReturnsAPromise().pipe(function( resolveValue ) {
        return functionThatReturnsAnotherPromise( resolveValue );
    });

chained.done(function() {
    // Both asynchronous operations done in sequence
});

希望这有助于。

这篇关于魔术JQuery的递延与一元符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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