簡體   English   中英

Node.js中的函數(err)回調

[英]function (err) callback in Node.js

我仍在嘗試着圍繞什么是函數回調及其工作原理。 我了解這是javascript的重要組成部分。 例如,來自node.js文檔的writeFile方法,此函數回調做什么? 此函數如何為err輸入?

fs.writeFile('message.txt', 'Hello Node', function (err) {
  if (err) throw err;
console.log('It\'s saved!');
});

fs.writeFile發生errorfs.writeFile會將error作為err傳遞給回調函數。

考慮這個例子

function wakeUpSnorlax(done) {

  // simulate this operation taking a while
  var delay = 2000;

  setTimeout(function() {

    // 50% chance for unsuccessful wakeup
    if (Math.round(Math.random()) === 0) {

      // callback with an error
      return done(new Error("the snorlax did not wake up!"));
    }

    // callback without an error
    done(null);        
  }, delay);
}

// reusable callback
function callback(err) {
  if (err) {
    console.log(err.message);
  }
  else {
    console.log("the snorlax woke up!");
  }
}

wakeUpSnorlax(callback); 
wakeUpSnorlax(callback); 
wakeUpSnorlax(callback); 

2秒后...

the snorlax did not wake up!
the snorlax did not wake up!
the snorlax woke up!

在上面的示例中, wakeUpSnorlax類似於fs.writeFile ,因為它完成fs.writeFile后需要調用一個回調函數。 如果fs.writeFile在執行任何過程中檢測到錯誤,則可以將Error發送給回調函數。 如果運行沒有問題,它將無錯誤地調用回調。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM