任何已建立的方便的 javascript 回调编写样式? [英] Any established convenient callback writing styles for javascript?

查看:24
本文介绍了任何已建立的方便的 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);

但是有很多传递变量一直在发生.与其他函数写在两者之间,这变得难以阅读.函数本身可能太微不足道,无法证明给它们自己的文件是合理的.

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.

推荐答案

一种不同的回调方法是 promises.

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

一个好处是,您可以模拟同步行为,因为您可以使用返回的承诺而不是提供对 $.ajax.success 的回调以及对回调和回调的回调....另一个优点是,您可以链接/聚合承诺,如果你愿意,可以为一个承诺聚合提供错误处理程序.

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.

我发现这篇文章很漂亮有用.它描述了回调、承诺和其他技术的优缺点.

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天全站免登陆