Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

javascript - Node.js: What techniques are there for writing clean, simple callback code?

node.js code is known for turning into callback spaghetti.

What are the best techniques for overcoming this problem and writing clean, uncomplex, easy to understand callback code in node.js?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Take a look at Promises: http://promises-aplus.github.io/promises-spec/

It is an open standard which intended to solve this issue.

I am using node module 'q', which implements this standard: https://github.com/kriskowal/q

Simple use case:

var Q = require('q');

For example we have method like:

var foo = function(id) {
  var qdef = Q.defer();

  Model.find(id).success(function(result) {
    qdef.resolve(result);
  });

  return (qdef.promise);
}

Then we can chain promises by method .then():

foo(<any-id>)
.then(function(result) {
  // another promise
})
.then(function() {
  // so on
});

It is also possible to creating promise from values like:

Q([]).then(function(val) { val.push('foo') });

And much more, see docs.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...