谁能给我一个简单的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/