为了账号安全,请及时绑定邮箱和手机立即绑定

nodeJs回调简单的例子

nodeJs回调简单的例子

青春有我 2019-08-12 10:34:17
nodeJs回调简单的例子任何人都可以给我一个nodeJs回调的简单例子,我已经在很多网站上搜索过相同但不能正确理解它,请给我一个简单的例子。getDbFiles(store, function(files){     getCdnFiles(store, function(files){     })})我想做那样的事....
查看完整描述

3 回答

?
LEATH

TA贡献1936条经验 获得超6个赞


var myCallback = function(data) {

  console.log('got data: '+data);

};


var usingItNow = function(callback) {

  callback('get it?');

};

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


最后在下一行使用它:


usingItNow(myCallback);

关于节点式错误约定


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

};

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


var usingItNow = function(callback) {

  var myError = new Error('My custom error!');

  callback(myError, 'get it?'); // I send my error as the first argument.

};

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


usingItNow(myCallback);

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


查看完整回答
反对 回复 2019-08-12
?
胡说叔叔

TA贡献1804条经验 获得超8个赞

这里是复制文本文件的例子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);
  });};

这是使用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!');
  }});

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

next(new Error('I cannot do it!')); // errornext(null, results); // no error occurred, return result


查看完整回答
反对 回复 2019-08-12
  • 3 回答
  • 0 关注
  • 609 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信