nodeJs 回调简单示例 [英] nodeJs callbacks simple example

查看:30
本文介绍了nodeJs 回调简单示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我一个nodeJs回调的简单例子,我已经在很多网站上搜索过,但无法正确理解它,请给我一个简单的例子.

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.

getDbFiles(store, function(files){
    getCdnFiles(store, function(files){
    })
})

我想做这样的事情...

I want to do something like that...

推荐答案

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);

关于节点样式错误约定

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

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
};

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

If we want to simulate an error case, we can define usingItNow like this

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);

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

The only difference in behavior would be contingent on which version of usingItNow you'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.

这篇关于nodeJs 回调简单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆