nodeJs 回调简单示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19739755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nodeJs callbacks simple example
提问by Bhushan Goel
can any one give me a a simple example of nodeJs callbacks, I have already searched for the same on many websites but not able to understand it properly, Please give me a simple example.
谁能给我一个nodeJs回调的简单例子,我已经在很多网站上搜索过,但无法正确理解它,请给我一个简单的例子。
getDbFiles(store, function(files){
getCdnFiles(store, function(files){
})
})
I want to do something like that...
我想做这样的事情...
回答by keyvan
var myCallback = function(data) {
console.log('got data: '+data);
};
var usingItNow = function(callback) {
callback('get it?');
};
Now open node or browser console and paste the above definitions.
现在打开节点或浏览器控制台并粘贴上述定义。
Finally use it with this next line:
最后在下一行中使用它:
usingItNow(myCallback);
With Respect to the Node-Style Error Conventions
关于节点样式错误约定
Costa asked what this would look like if we were to honor the node error callback conventions.
科斯塔问如果我们遵守节点错误回调约定,这会是什么样子。
In this convention, the callback should expect to receive at least one argument, the first argument, as an error. Optionally we will have one or more additional arguments, depending on the context. In this case, the context is our above example.
在这个约定中,回调应该期望接收至少一个参数,第一个参数,作为错误。可选地,我们将有一个或多个附加参数,具体取决于上下文。在这种情况下,上下文就是我们上面的例子。
Here I rewrite our example in this convention.
在这里,我在此约定中重写了我们的示例。
var myCallback = function(err, data) {
if (err) throw err; // Check for the error and throw if it exists.
console.log('got data: '+data); // Otherwise proceed as usual.
};
var usingItNow = function(callback) {
callback(null, 'get it?'); // I dont want to throw an error, so I pass null for the error argument
};
If we want to simulate an error case, we can define usingItNow like this
如果我们想模拟一个错误情况,我们可以像这样定义 usingItNow
var usingItNow = function(callback) {
var myError = new Error('My custom error!');
callback(myError, 'get it?'); // I send my error as the first argument.
};
The final usage is exactly the same as in above:
最后的用法和上面的完全一样:
usingItNow(myCallback);
The only difference in behavior would be contingent on which version of usingItNowyou've defined: the one that feeds a "truthy value" (an Error object) to the callback for the first argument, or the one that feeds it null for the error argument.
行为的唯一区别取决于usingItNow您定义的版本:将“真实值”(一个 Error 对象)提供给第一个参数的回调的那个,或者为 error 参数提供 null 的那个.
回答by Chev
A callback function is simply a function you pass into another function so that function can call it at a later time. This is commonly seen in asynchronous APIs; the API call returns immediately because it is asynchronous, so you pass a function into it that the API can call when it's done performing its asynchronous task.
回调函数只是您传递给另一个函数的函数,以便该函数可以在以后调用它。这在异步API 中很常见;API 调用会立即返回,因为它是异步的,因此您将一个函数传递给它,API 在完成异步任务后可以调用该函数。
The simplest example I can think of in JavaScript is the setTimeout()function. It's a global function that accepts two arguments. The first argument is the callback function and the second argument is a delay in milliseconds. The function is designed to wait the appropriate amount of time, then invoke your callback function.
我能想到的 JavaScript 中最简单的例子就是setTimeout()函数。这是一个接受两个参数的全局函数。第一个参数是回调函数,第二个参数是以毫秒为单位的延迟。该函数旨在等待适当的时间,然后调用您的回调函数。
setTimeout(function () {
console.log("10 seconds later...");
}, 10000);
You may have seen the above code before but just didn't realize the function you were passing in was called a callback function. We could rewrite the code above to make it more obvious.
您之前可能已经看过上面的代码,但只是没有意识到您传入的函数被称为回调函数。我们可以重写上面的代码,让它更明显。
var callback = function () {
console.log("10 seconds later...");
};
setTimeout(callback, 10000);
Callbacks are used all over the place in Node because Node is built from the ground up to be asynchronous in everything that it does. Even when talking to the file system. That's why a ton of the internal Node APIs accept callback functions as arguments rather than returning data you can assign to a variable. Instead it will invoke your callback function, passing the data you wanted as an argument. For example, you could use Node's fslibrary to read a file. The fsmodule exposes two unique API functions: readFileand readFileSync.
回调在 Node 中随处可见,因为 Node 是从头开始构建的,它所做的一切都是异步的。即使在与文件系统交谈时。这就是为什么大量内部 Node API 接受回调函数作为参数而不是返回可以分配给变量的数据。相反,它会调用您的回调函数,将您想要的数据作为参数传递。例如,您可以使用 Node 的fs库来读取文件。该fs模块公开了两个独特的 API 函数:readFile和readFileSync.
The readFilefunction is asynchronous while readFileSyncis obviously not. You can see that they intend you to use the async calls whenever possible since they called them readFileand readFileSyncinstead of readFileand readFileAsync. Here is an example of using both functions.
该readFile函数是异步的,而readFileSync显然不是。您可以看到他们希望您尽可能使用异步调用,因为他们调用它们readFile而readFileSync不是readFileand readFileAsync。这是使用这两个函数的示例。
Synchronous:
同步:
var data = fs.readFileSync('test.txt');
console.log(data);
The code above blocks thread execution until all the contents of test.txtare read into memory and stored in the variable data. In node this is typically considered bad practice. There are times though when it's useful, such as when writing a quick little script to do something simple but tedious and you don't care much about saving every nanosecond of time that you can.
上面的代码阻止线程执行,直到 的所有内容test.txt都读入内存并存储在变量中data。在节点中,这通常被认为是不好的做法。但有时它很有用,例如在编写一个快速的小脚本来完成一些简单但乏味的事情时,您不太关心如何节省每一纳秒的时间。
Asynchronous (with callback):
异步(带回调):
var callback = function (err, data) {
if (err) return console.error(err);
console.log(data);
};
fs.readFile('test.txt', callback);
First we create a callback function that accepts two arguments errand data. One problem with asynchronous functions is that it becomes more difficult to trap errors so a lot of callback-style APIs pass errors as the first argument to the callback function. It is best practice to check if errhas a value before you do anything else. If so, stop execution of the callback and log the error.
首先我们创建一个回调函数,它接受两个参数err和data。异步函数的一个问题是捕获错误变得更加困难,因此许多回调风格的 API 将错误作为第一个参数传递给回调函数。最好的做法err是在做任何其他事情之前检查是否有值。如果是,请停止执行回调并记录错误。
Synchronous calls have an advantage when there are thrown exceptions because you can simply catch them with a try/catchblock.
当抛出异常时,同步调用具有优势,因为您可以简单地用try/catch块捕获它们。
try {
var data = fs.readFileSync('test.txt');
console.log(data);
} catch (err) {
console.error(err);
}
In asynchronous functions it doesn't work that way. The API call returns immediately so there is nothing to catch with the try/catch. Proper asynchronous APIs that use callbacks will always catch their own errors and then pass those errors into the callback where you can handle it as you see fit.
在异步函数中,它不是那样工作的。API 调用会立即返回,因此try/catch. 使用回调的正确异步 API 将始终捕获它们自己的错误,然后将这些错误传递到回调中,您可以在其中根据需要处理它。
In addition to callbacks though, there is another popular style of API that is commonly used called the promise. If you'd like to read about them then you can read the entire blog post I wrote based on this answer here.
但是,除了回调之外,还有另一种流行的 API 样式,通常称为承诺。如果您想了解他们,那么你可以阅读整个博客文章中,我根据这个答案写在这里。
回答by Leonid Beschastny
Here is an example of copying text file with fs.readFileand fs.writeFile:
这里是复制文本文件的例子fs.readFile和fs.writeFile:
var fs = require('fs');
var copyFile = function(source, destination, next) {
// we should read source file first
fs.readFile(source, function(err, data) {
if (err) return next(err); // error occurred
// now we can write data to destination file
fs.writeFile(destination, data, next);
});
};
And that's an example of using copyFilefunction:
这是一个使用copyFile函数的例子:
copyFile('foo.txt', 'bar.txt', function(err) {
if (err) {
// either fs.readFile or fs.writeFile returned an error
console.log(err.stack || err);
} else {
console.log('Success!');
}
});
Common node.js pattern suggests that the first argument of the callback function is an error. You should use this pattern because all control flow modules rely on it:
常见的 node.js 模式表明回调函数的第一个参数是一个错误。您应该使用此模式,因为所有控制流模块都依赖于它:
next(new Error('I cannot do it!')); // error
next(null, results); // no error occurred, return result
回答by spacedev
Try this example as simple as you can read, just copy save newfile.js do node newfile to run the application.
尽可能简单地尝试这个例子,只需复制 save newfile.js do node newfile 来运行应用程序。
function myNew(next){
console.log("Im the one who initates callback");
next("nope", "success");
}
myNew(function(err, res){
console.log("I got back from callback",err, res);
});
回答by saurabh kumar
we are creating a simple function as
我们正在创建一个简单的函数
callBackFunction (data, function ( err, response ){
console.log(response)
})
// callbackfunction
function callBackFuntion (data, callback){
//write your logic and return your result as
callback("",result) //if not error
callback(error, "") //if error
}
回答by Anuj Kumar
const fs = require('fs');
fs.stat('input.txt', function (err, stats) {
if(err){
console.log(err);
} else {
console.log(stats);
console.log('Completed Reading File');
}
});
'fs' is a node module which helps you to read file. Callback function will make sure that your file named 'input.txt' is completely read before it gets executed. fs.stat() function is to get file information like file size, date created and date modified.
'fs' 是一个节点模块,可帮助您读取文件。回调函数将确保在执行之前完全读取名为“input.txt”的文件。fs.stat() 函数用于获取文件信息,如文件大小、创建日期和修改日期。
回答by Surojit Paul
//delay callback function
function delay (seconds, callback){
setTimeout(() =>{
console.log('The long delay ended');
callback('Task Complete');
}, seconds*1000);
}
//Execute delay function
delay(1, res => {
console.log(res);
})
回答by Dan Watts
This blog-post has a good write-up:
这篇博文写得很好:
https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced
https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced
function doHomework(subject, callback) {
alert(`Starting my ${subject} homework.`);
callback();
}
function alertFinished(){
alert('Finished my homework');
}
doHomework('math', alertFinished);
回答by toondaey
A callbackis a function passed as an parameter to a Higher Order Function(wikipedia). A simple implementation of a callback would be:
Acallback是作为参数传递给 a Higher Order Function( wikipedia)的函数。回调的一个简单实现是:
const func = callback => callback('Hello World!');
To call the function, simple pass another function as argument to the function defined.
要调用该函数,只需将另一个函数作为参数传递给定义的函数即可。
func(string => console.log(string));

