本文介绍了异步JavaScript - 回调与延迟/承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在努力提高我的JavaScript应用程序的质量。

Lately I've been making an effort to improve the quality of my JavaScript applications.

一种模式我我们采用的是使用单独的数据上下文对象来为我的应用程序加载数据(之前我在我的视图模型中直接执行此操作)。

One pattern I've adopted is to use a separate "data context" object to load data for my application (previously I was doing this directly in my view models).

以下示例返回在客户端上初始化的数据:

The following example returns data that is initialized on the client:

var mockData = (function($, undefined) {

    var fruit = [
        "apple",
        "orange",
        "banana",
        "pear"
        ];

    var getFruit = function() {
        return fruit;
    };

    return {
        getFruit: getFruit
    }
})(jQuery);

在大多数情况下,我们将从服务器加载数据,因此我们无法立即返回响应。我们在API中处理这个问题似乎有两种选择:

In most cases we'll be loading data from the server so we can't return an immediate response. It seems I have two options for how we handle this in our API:


  1. 使用回调

  2. 返回。

  1. Using a callback
  2. Returning a promise.

以前我总是使用回调方法:

Previously I'd always used the callback approach:

var getFruit = function(onFruitReady) {
    onFruitReady(fruit);
};

// ...

var FruitModel = function(dataContext, $) {
    return {
        render: function() {
            dataContext.getFruit(function(fruit) {
                // do something with fruit
            });
        }
    };
};

然而,我可以看到如何最终回调地狱,特别是在构建复杂的JavaScript应用程序时。

However, I can see how it's possible to end up in callback hell, especially when building complex JavaScript applications.

然后我遇到了Promises的设计模式。我不是要求调用者提供回调,而是返回可以观察到的承诺:

Then I came across the Promises design pattern. Instead of requiring the caller to supply a callback, I instead return a "promise" that can be observed:

var getFruit = function() {
    return $.Deferred().resolve(fruit).promise();
};

// ...
dataContext.getFruit().then(function(fruit) {
    // do something with fruit
});

我可以看到使用这种模式的明显好处,特别是因为我可以等待关于多个延迟对象,这在加载单页应用程序的初始化数据时非常有用。

I can see obvious benefits of using this pattern, especially since I can wait on multiple deferred objects which could be very useful when loading initialization data for a single page application.

但是,我很想理解在我开始使用愤怒之前,每种模式的利弊。我也对这是否是其他库的方向感兴趣。似乎是jQuery的情况。

However, I'm keen to understand the pros and cons of each pattern before I start to use either in anger. I'm also interested in whether this is the direction other libraries are going in. It seems to be the case with jQuery.

这是一个到我用来测试的小提琴。

Here's a link to the fiddle I'm using for testing.

推荐答案

Promise也依赖于场景背后的回调,所以它并不是真正的回调。

Promises also rely on callbacks behind the scene, so it's not really one vs. the other.

回调的好处是它们很容易用纯JavaScript实现(例如在ajax调用中)。

The benefit of callbacks is that they are easy to implement with plain JavaScript (for example in ajax calls).

Promises需要一个额外的抽象层,这通常意味着你将依赖一个库(在您的情况下不是问题,因为您已经在使用jQuery)。当你并行处理多个异步调用时,它们是完美的。

Promises require an additional abstraction layer, which usually means that you'll rely on a library (not an issue in your case as you are already using jQuery). They are perfect when you deal with multiple async calls in parallel.

这篇关于异步JavaScript - 回调与延迟/承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 15:01