Node-02.异步之回调函数callback

151 阅读1分钟

1.异步之回调函数callback

  • 也就是说,回调函数中的第一个参数必须是错误

回调函数例子:

interview(function(){
  console.log('笑一个吧')
})

function interview(callback){
  setTimeout(()=>{
    callback('success')
  },500)
}

2.异步任务的错误不能够被外面的try-catch察觉

try {
  interview(function () {
    console.log('笑一个吧');
  });
} catch (error) {
  console.log('我是error',error);
}

function interview(callback) {
  setTimeout(() => {
    if (Math.random() < 0.8) {
      callback('success');
    } else {
      throw new Error();
    }
  }, 500);
}

执行node index.js后,发现报错如下

  • 如上代码例子,通过throw new Error()抛出的错误,并没有被外面的try-catch捕获到

🚀解决方案:

也是需要使用callback错误❎或者正确✅结果返回

  interview(function (res) {
    if(res instanceof Error){
      return console.log('不可放弃的努力');
    }
    console.log('笑一个吧');
  });

function interview(callback) {
  setTimeout(() => {
    if (Math.random() < 0.5) {
      callback('success');
    } else {
      callback(new Error('挑战失败了'));
    }
  }, 500);
}