nodeJs回调简单的例子

Bhu*_*oel 113 javascript asynchronous callback asynccallback node.js

任何人都可以给我一个nodeJs回调的简单例子,我已经在很多网站上搜索过相同但不能正确理解它,请给我一个简单的例子.

getDbFiles(store, function(files){
    getCdnFiles(store, function(files){
    })
})
Run Code Online (Sandbox Code Playgroud)

我想做那样的事......

key*_*van 185

var myCallback = function(data) {
  console.log('got data: '+data);
};

var usingItNow = function(callback) {
  callback('get it?');
};
Run Code Online (Sandbox Code Playgroud)

现在打开节点或浏览器控制台并粘贴上面的定义.

最后在下一行使用它:

usingItNow(myCallback);
Run Code Online (Sandbox Code Playgroud)

关于节点式错误约定

Costa问我们如果要遵守节点错误回调约定会是什么样子.

在此约定中,回调应该期望至少接收一个参数,即第一个参数,作为错误.可选地,我们将具有一个或多个附加参数,具体取决于上下文.在这种情况下,上下文是我们上面的例子.

在这里,我在这个约定中重写了我们的例子.

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
};
Run Code Online (Sandbox Code Playgroud)

如果我们想模拟错误情况,我们可以像这样定义usingItNow

var usingItNow = function(callback) {
  var myError = new Error('My custom error!');
  callback(myError, 'get it?'); // I send my error as the first argument.
};
Run Code Online (Sandbox Code Playgroud)

最终用法与上面完全相同:

usingItNow(myCallback);
Run Code Online (Sandbox Code Playgroud)

行为的唯一区别取决于usingItNow您定义的版本:向第一个参数的回调提供"truthy值"(一个Error对象)的那个,或者为错误参数提供null的那个版本. .


Che*_*hev 107

回调函数只是一个传递给另一个函数的函数,以便函数可以在以后调用它.这在异步API中很常见; API调用立即返回,因为它是异步的,因此您将一个函数传递给它,当API完成它的异步任务时,它可以调用它.

我在JavaScript中可以想到的最简单的例子就是setTimeout()函数.它是一个接受两个参数的全局函数.第一个参数是回调函数,第二个参数是以毫秒为单位的延迟.该函数旨在等待适当的时间,然后调用您的回调函数.

setTimeout(function () {
  console.log("10 seconds later...");
}, 10000);
Run Code Online (Sandbox Code Playgroud)

您之前可能已经看过上面的代码但是没有意识到您传入的函数被称为回调函数.我们可以重写上面的代码,使其更加明显.

var callback = function () {
  console.log("10 seconds later...");
};
setTimeout(callback, 10000);
Run Code Online (Sandbox Code Playgroud)

回调在Node中的所有位置都使用,因为Node从头开始构建,在它所做的每件事中都是异步的.即使在与文件系统交谈时也是如此.这就是为什么大量内部Node API接受回调函数作为参数而不是返回可以分配给变量的数据的原因.相反,它将调用您的回调函数,将您想要的数据作为参数传递.例如,您可以使用Node的fs库来读取文件.该fs模块公开了两个独特的API函数:readFilereadFileSync.

readFile函数是异步的,但readFileSync显然不是.您可以看到他们打算尽可能使用异步调用,因为他们调用了它们readFilereadFileSync不是readFilereadFileAsync.以下是使用这两种功能的示例.

同步:

var data = fs.readFileSync('test.txt');
console.log(data);
Run Code Online (Sandbox Code Playgroud)

上面的代码阻止线程执行,直到所有内容test.txt都被读入内存并存储在变量中data.在节点中,这通常被认为是不好的做法.有时候它很有用,比如写一个快速的小脚本来做一些简单而又单调乏味的事情,而你却不太关心每个纳秒的时间.

异步(带回调):

var callback = function (err, data) {
  if (err) return console.error(err);
  console.log(data);
};
fs.readFile('test.txt', callback);
Run Code Online (Sandbox Code Playgroud)

首先,我们创建一个接受两个参数的回调函数errdata.异步函数的一个问题是陷阱错误变得更加困难,因此许多回调式API将错误作为回调函数的第一个参数传递.最佳做法err是在执行任何其他操作之前检查是否具有值.如果是,则停止执行回调并记录错误.

当存在抛出异常时,同步调用具有优势,因为您可以使用try/catch块捕获它们.

try {
  var data = fs.readFileSync('test.txt');
  console.log(data);
} catch (err) {
  console.error(err);
}
Run Code Online (Sandbox Code Playgroud)

在异步函数中,它不能以这种方式工作.API调用立即返回,因此没有什么可以捕获的try/catch.使用回调的正确异步API将始终捕获自己的错误,然后将这些错误传递到回调中,您可以根据需要处理它.

除了回调之外,还有另一种流行的API风格,通常称为promise.如果你想阅读它们,那么你可以在这里根据这个答案阅读我写的整篇博文.

  • 这个概念非常精致而简洁; 对于像我这样的node.js启动器...... (3认同)
  • +1用于提供大量上下文.不仅回调函数看起来像什么,而且它们是什么,为什么使用它们,以及为什么它们被大量使用.对初学者真的很有帮助. (3认同)

Leo*_*tny 11

这里是复制文本文件的例子fs.readFilefs.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);
  });
};
Run Code Online (Sandbox Code Playgroud)

这是使用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!');
  }
});
Run Code Online (Sandbox Code Playgroud)

公共node.js模式表明回调函数的第一个参数是错误.您应该使用此模式,因为所有控制流模块都依赖于它:

next(new Error('I cannot do it!')); // error

next(null, results); // no error occurred, return result
Run Code Online (Sandbox Code Playgroud)

  • @SemicolonWarrier是我和其他人的指针:http://stackoverflow.com/questions/5384526/javascript-node-js-next (3认同)
  • 接下来是什么?什么是变量结果=被称为什么? (2认同)

spa*_*dev 7

尝试这个例子就像你可以阅读一样简单,只需复制save newfile.js做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);
});
Run Code Online (Sandbox Code Playgroud)