reject in promise undefined

删除回忆录丶 提交于 2019-12-12 02:46:29

问题


I tried below function use co and javascript promise test, the fulfill will success return but reject not, and catch error undefined. and the flow can't continue. why?

Error:

> at GeneratorFunctionPrototype.next (native)
    at onFulfilled (/Users/../project/app/node_modules/co/index.js:65:19)
    at runMicrotasksCallback (node.js:337:7)
    at process._tickDomainCallback (node.js:381:11)

Code:

domain.run(function() {

  var testPromise = function() {
    return new Promise(function (fulfill, reject){
      //reject('error');
      reject(new Error('message'));
    });
  };


co(function *() {
  var d = yield testPromise();
  console.log(d);
  res.send('fin');
}).catch(onerror);
function onerror(error) { console.error(error.stack); }

});
domain.on('error', function(error) { console.error(error); });

回答1:


catch error undefined

No. It catches the error 'error', the value you rejected with. Of course, it's not really an Error but a string, and as such it does not have a .stack property - that's why it logs undefined. Fix your code by doing

reject(new Error('…'));

See also Should a Promise.reject message be wrapped in Error?

the flow can't continue. why?

Well, because you've got an error, and thrown exceptions do have this behaviour. You'll also want to send a response in your error handler!

co(function *() {
  …
}).catch(function onerror(error) {
  console.error(error.stack);
  res.send('err');
});

Or if you intend to continue the flow at the call, put the .catch handler right there:

co(function *() {
  yield testPromise().then(function(d) {
    console.log(d);
  }).catch(function(error) {
    console.error(error.stack);
  });
  res.send('fin');
});

Alternatively, wrap your promise call in a try-catch:

co(function *() {
  try {
    var d = yield testPromise();
    console.log(d);
  } catch(error) {
    console.error(error.stack);
  }
  res.send('fin');
});


来源:https://stackoverflow.com/questions/32215492/reject-in-promise-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!