javascript - nodeJs 回调简单示例

标签 javascript node.js asynchronous callback asynccallback

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

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

我想做这样的事情...

最佳答案

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

var usingItNow = function(callback) {
  callback('get it?');
};

现在打开 Node 或浏览器控制台并粘贴上述定义。

最后将其与下一行一起使用:

usingItNow(myCallback);

关于 Node 样式错误约定

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

在此约定中,回调应该接收至少一个参数,即第一个参数,作为错误。我们可以选择有一个或多个附加参数,具体取决于上下文。在本例中,上下文就是我们上面的示例。

在这里我重写了这个约定中的示例。

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 版本:为第一个参数的回调提供“真值”(Error 对象)的版本,或为错误参数提供 null 的版本。

关于javascript - nodeJs 回调简单示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51178887/

相关文章:

node.js - 使用 node.js 时无法使用 jsPDF 添加图像

node.js - 我如何在 Node js 中读取、写入/附加 xls 文件

javascript - 将 React 与带有 JSX 的现有应用程序一起使用

c# - C# 中类型安全的即发即弃异步委托(delegate)调用

Javascript 函数正确运行 8 次,然后每隔一次

javascript - 选择器中的 CSS 类规范

javascript - For 在主干集合上循环

c# - 接收并发异步请求并一次处理一个请求

c# - 使用 NetworkStream.BeginRead 和 NetworkStream.EndRead 实现超时

javascript - D3 缩放不起作用