使用Koa中的promise进行错误处理

Dav*_*vid 3 node.js koa

如果我在Koa中作出承诺,他们可能会被拒绝:

function fetch = (){
  var deferred = q.defer(); 
  //Some async action which calls deferred.reject();
  return deferred.promise;
}

this.body = yield fetch(); //bad, not going to work
Run Code Online (Sandbox Code Playgroud)

Koa中是否存在一个错误处理模式来处理这个问题,除了明确地展开promise then和明确处理错误?

Jam*_*ore 6

试着抓.在引擎盖下koajs使用co.查看co的文档,它更好地描述了错误处理.

function fetch = (){
  var deferred = q.defer(); 
  //Some async action which calls deferred.reject();
  return deferred.promise;
}
try{
    this.body = yield fetch(); //bad, not going to work
}
catch(err){
    this.throw('something exploded');
}
Run Code Online (Sandbox Code Playgroud)

以下是该承诺所发生的事情的基本示例:

function * someGenerator () {
  let result;
  try{
    result = yield fetch();
    console.log('won\'t make it here...');
  }
  catch(err){
    console.log(err);
  }
  console.log('will make it here...');
}
// Normally co() does everything below this line, I'm including it for
// better understanding

// instantiate the generator
let gen = someGenerator();
// calling gen.next() starts execution of code up until the first yield
// or the function returns.  
let result = gen.next();
// the value returned by next() is an object with 2 attributes
// value is what is returned by the yielded item, a promise in your example
// and done which is a boolean that indicates if the generator was run 
// to completion
// ie result = {value: promise, done: false}

// now we can just call the then function on the returned promise
result.value.then(function(result){
  // calling .next(result) restarts the generator, returning the result
  // to the left of the yield keyword
  gen.next(result);
}, function(err){
  // however if there happened to be an error, calling gen.throw(err)
  // restarts the generator and throws an error that can be caught by 
  // a try / catch block.  
  // This isn't really the intention of generators, just a clever hack
  // that allows you to code in a synchronous style (yet still async code)
  gen.throw(err);
});
Run Code Online (Sandbox Code Playgroud)

如果你仍然不确定,这里还有其他一些可能会有所帮助的事情:

观看我在JavaScript生成器上的截屏视频:http://knowthen.com/episode-2-understanding-javascript-generators/

和/或尝试以下代码:

// test.js
'use strict';
let co      = require('co'),
    Promise = require('bluebird');

function fetch () {
  let deffered = Promise.defer();
  deffered.reject(new Error('Some Error'));
  return deffered.promise;
}

co.wrap(function *(){
  let result;
  try{
    result = yield fetch();
    console.log('won\'t make it here...');
  }
  catch(err){
    console.log(err);
  }
  console.log('will make it here...');

})();
Run Code Online (Sandbox Code Playgroud)

然后在控制台上运行

$ node test.js
[Error: Some Error]
will make it here...
Run Code Online (Sandbox Code Playgroud)