亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

nodeJs回調簡單的例子

nodeJs回調簡單的例子

青春有我 2019-08-12 10:34:17
nodeJs回調簡單的例子任何人都可以給我一個nodeJs回調的簡單例子,我已經在很多網站上搜索過相同但不能正確理解它,請給我一個簡單的例子。getDbFiles(store, function(files){     getCdnFiles(store, function(files){     })})我想做那樣的事....
查看完整描述

3 回答

?
LEATH

TA貢獻1936條經驗 獲得超7個贊


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 關注
  • 682 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號