任何已建立方便的回调写作风格的javascript? [英] Any established convenient callback writing styles for javascript?

查看:96
本文介绍了任何已建立方便的回调写作风格的javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

回调在编码中越来越需要,特别是当你考虑 Node.JS 非阻塞的工作方式时。

Callbacks are more and more a requirement in coding, especially when you think about Node.JS non-blocking style of working. But writing a lot of coroutine callbacks quickly becomes difficult to read back.

例如,假设这样的东西金字塔的末日

For example, imagine something like this Pyramid Of Doom:

// This asynchronous coding style is really annoying. Anyone invented a better way yet?
// Count, remove, re-count (verify) and log.
col.count(quertFilter,          function(err, countFiltered) {
    col.count(queryCached,      function(err, countCached) {
        col.remove(query,       function(err) {
            col.count(queryAll, function(err, countTotal) {
                util.log(util.format('MongoDB cleanup: %d filtered and %d cached records removed. %d last-minute records left.', countFiltered, countCached, countTotal));
            });
        });
    });
});

是我们经常看到的,很容易变得更加复杂。

is something we see often and can easily become more complex.

当每个函数至少有几行更长的时间,它开始变得可行,分开的功能:

When every function is at least a couple of lines longer, it starts to become feasible to separate the functions:

// Imagine something more complex

function mary(data, pictures) {
    // Do something drastic
}

// I want to do mary(), but I need to write how before actually starting.

function nana(callback, cbFinal) {
    // Get stuff from database or something
    callback(nene, cbFinal, data);
}

function nene(callback, cbFinal, data) {
    // Do stuff with data
    callback(nini, cbFinal, data);
}

function nini(callback, data) {
    // Look up pictures of Jeff Atwood
    callback(data, pictures);
}

// I start here, so this story doesn't read like a book even if it's quite straightforward.

nana(nene, mary);

但是有很多传递vars的事情。与其他函数之间写,这变得很难阅读。

But there is a lot of passing vars around happening all the time. With other functions written in between, this becomes hard to read. The functions itself might be too insignificant on their own to justify giving them their own file.

推荐答案

回调的另一种方法是promise 。

A different approach to callbacks are promises.

示例:jQuery Ajax。这可能看起来很熟悉。

Example: jQuery Ajax. this one might look pretty familiar.

$.ajax({
  url: '/foo',
  success: function() {
      alert('bar');
  }  
});

但$ .ajax也返回一个promise。

But $.ajax also returns a promise.

var request = $.ajax({
  url: '/foo'
});

request.done(function() {
    alert('bar');
});

一个好处是,你模拟同步行为,因为你可以使用返回的promise,回调到$ .ajax.success和一个回调的回调和回调....另一个优点是,你可以链接/聚合promises,并有一个promise-aggregate的错误处理程序,如果你喜欢。

A benefit is, that you simulate synchronous behavior, because you can use the returned promise instead of providing a callback to $.ajax.success and a callback to the callback and a callback.... Another advantage is, that you can chain / aggregate promises, and have error handlers for one promise-aggregate if you like.

我发现这篇文章非常有用。
它描述了回调,promise和其他技术的利弊。

I found this article to be pretty useful. It describes the pro and cons of callbacks, promises and other techniques.

一个流行的实现(例如AngularJS iirc使用)是 Q

A popular implementation (used by e.g. AngularJS iirc) is Q.

这篇关于任何已建立方便的回调写作风格的javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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