callback style與promise的整合

在需要呼叫多次callback時,async await可改善callback hell的現象
而nodejs在8.x支援原生的async await,在設計callback api時,可設計成同時支援舊的callback style與新的promise style,這樣一來可以使api同時支援’async’ library與async/await語法

作法1:

function delay(ms, cb){
  var func = delay;
  if(cb === undefined){
    //檢查是否有callback,如果沒有返回promise 
    return new Promise(function(resolve, reject){
      func(ms, function(err, data){
        if(err) return reject(err);
        resolve(data);
      });
    });
  }
  setTimeout(function(){ cb(null, Date.now()); }, ms); 
}

作法2: 參考: https://zaiste.net/node_js_functions_simultaneously_supporting_callbacks_promises/

function delay(ms, cb = function(){}){
  var func = delay;
  return new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve(Date.now());
      cb(null, Date.now());
    }, ms);
  });
}

使用:

//callback用法
delay(2000, function(err, data){
  if(err){
    console.log('error', err);
  } else {
    console.log(data);
  }
});
//promise then用法
delay(2000).then(data => console.log(data)).catch(err => console.log('error', err));

//async await用法,await要包在async function內
(async function(){
  try{
    var resp = await delay(2000); //resolve時才往下走
    console.log(resp);
  }catch(e){
    console.log('error', e);
  }
})();
This entry was posted in nodejs. Bookmark the permalink.

Leave a Reply