nodeJs回调简单的例子

nodeJs回调简单的例子

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

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

我想做那样的事....


青春有我
浏览 615回答 3
3回答

LEATH

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};如果我们想模拟错误情况,我们可以像这样定义usingItNowvar 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的那个版本。 。

胡说叔叔

这里是复制文本文件的例子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);   });};这是使用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
打开App,查看更多内容
随时随地看视频慕课网APP