Callback Hell-Javascript非同期プログラミング指導
19193 ワード
--まず抜粋して、翻訳を待ちます.
What is「calback hell」?
Aynchronous javascript、or javascript that uss calbacks、is hard to get right intuitively.A lot of code ends up looking like this:
Writing better code isn't that hard!You only need to know about a few things:
Name your functions
Here is some(messy)browser javascript that uses browser-request to make an AJAX request to a server:
makes code easer to readwhen exceptions happen you will get stacktracces that reference actual function names instead of「anonymous」allows you to keep your code show,or not neted deeply,which brigs me to my next point:Keep your code show
Buiilding on the last example、let's go a bit further and get rid of the triple level neting that is going on in the code:
Modularize
This is the most import part: Anyone is capable of creating modules (AKA libries).Toquot te Isaac Schlueter (of the node.js project): 「Write small modules that each do one thing,and asemble them into other modules that do a biggar thing.You can't get into calback hell don't go there.」
Let's Tate the boilerplate code from above and turn it indule by spliting it up into a couple of files.Since I write JavaScript in both the browser and on the server,I'll show a methboth bonit
Here is a new file caled
To use Common JS modules in the browser you can use a command line thing caled browserify.I won't go into the details on how to use it here but it lets you use
Now that we have
ease ier for new developers to understand--they won't get boged down by having to read through all of the
I still don't get it
Try reading my introduction to calbacks.
What about promises?
Promises ara more abstract pattern of working with async code in JavaScript.
The scope of this document is to show how to write vanilla javascript.If you use a third party library that adds abstraction to your JS then make sure you're willing to force everryone that contributes to to vitributes to your theriar save.
In my own personal experience I use calbacks for 90%of the async code I write and when things get hairy I bring in something like the async library.
That being said、evryone develops their own unique JavaScript style and ou shound do what you like.Just remember that there re re re absome people like to use onlycalbacks、some people don't.
From http://callbackhell.com/
What is「calback hell」?
Aynchronous javascript、or javascript that uss calbacks、is hard to get right intuitively.A lot of code ends up looking like this:
fs.readdir(source, function(err, files) {
if (err) {
console.log('Error finding files: ' + err)
} else {
files.forEach(function(filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function(err, values) {
if (err) {
console.log('Error identifying file size: ' + err)
} else {
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach(function(width, widthIndex) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(destination + 'w' + width + '_' + filename, function(err) {
if (err) console.log('Error writing file: ' + err)
})
}.bind(this))
}
})
})
}
})
See all the instances of function
and })
EekThis is affectional known as calback hell.Writing better code isn't that hard!You only need to know about a few things:
Name your functions
Here is some(messy)browser javascript that uses browser-request to make an AJAX request to a server:
var form = document.querySelector('form')
form.onsubmit = function(submitEvent) {
var name = document.querySelector('input').value
request({
uri: "http://example.com/upload",
body: name,
method: "POST"
}, function(err, response, body) {
var statusMessage = document.querySelector('.status')
if (err) return statusMessage.value = err
statusMessage.value = body
})
}
This code has twonymous functions.Let's give em names!var form = document.querySelector('form')
form.onsubmit = function formSubmit(submitEvent) {
var name = document.querySelector('input').value
request({
uri: "http://example.com/upload",
body: name,
method: "POST"
}, function postResponse(err, response, body) {
var statusMessage = document.querySelector('.status')
if (err) return statusMessage.value = err
statusMessage.value = body
})
}
As You can see naming functions superease and does some nine to your code:makes code easer to readwhen exceptions happen you will get stacktracces that reference actual function names instead of「anonymous」allows you to keep your code show,or not neted deeply,which brigs me to my next point:Keep your code show
Buiilding on the last example、let's go a bit further and get rid of the triple level neting that is going on in the code:
function formSubmit(submitEvent) {
var name = document.querySelector('input').value
request({
uri: "http://example.com/upload",
body: name,
method: "POST"
}, postResponse)
}
function postResponse(err, response, body) {
var statusMessage = document.querySelector('.status')
if (err) return statusMessage.value = err
statusMessage.value = body
}
document.querySelector('form').onsubmit = formSubmit
Code like this is less scary to look at and is easure to edit,refactor and hack on later.Modularize
This is the most import part: Anyone is capable of creating modules (AKA libries).Toquot te Isaac Schlueter (of the node.js project): 「Write small modules that each do one thing,and asemble them into other modules that do a biggar thing.You can't get into calback hell don't go there.」
Let's Tate the boilerplate code from above and turn it indule by spliting it up into a couple of files.Since I write JavaScript in both the browser and on the server,I'll show a methboth bonit
Here is a new file caled
formuploader.js
that contains our two functions from before:function formSubmit(submitEvent) {
var name = document.querySelector('input').value
request({
uri: "http://example.com/upload",
body: name,
method: "POST"
}, postResponse)
}
function postResponse(err, response, body) {
var statusMessage = document.querySelector('.status')
if (err) return statusMessage.value = err
statusMessage.value = body
}
exports.submit = formSubmit
The exports
ビットat the end is an example of the CommunJS module system,which is used by Node.js for server side javascript programming.I quite of module s because is it is so simple--you only have the defidule the halt halt halt halt halt halt halt halt haire exports
thing isTo use Common JS modules in the browser you can use a command line thing caled browserify.I won't go into the details on how to use it here but it lets you use
require
to load modules into your programs.Now that we have
formuploader.js
(and it is loaded in the page as a script()we just need to require it and use it!Here is how our appication specific code look s now:var formUploader = require('formuploader')
document.querySelector('form').onsubmit = formUploader.submit
Now our aplication is only two lineas of code and has the follwing benefits:ease ier for new developers to understand--they won't get boged down by having to read through all of the
formuploader
functionsformuploader
can get used in other placces without duplicating code and can easure be shared on githubthe code itself is nice and simple and easy to readThe re are lots of module patterns for web browser and on the server.Some of them get very coplicated.The ones shown here what I consider to be the simplest to understand.I still don't get it
Try reading my introduction to calbacks.
What about promises?
Promises ara more abstract pattern of working with async code in JavaScript.
The scope of this document is to show how to write vanilla javascript.If you use a third party library that adds abstraction to your JS then make sure you're willing to force everryone that contributes to to vitributes to your theriar save.
In my own personal experience I use calbacks for 90%of the async code I write and when things get hairy I bring in something like the async library.
That being said、evryone develops their own unique JavaScript style and ou shound do what you like.Just remember that there re re re absome people like to use onlycalbacks、some people don't.
From http://callbackhell.com/