use*_*888 0 javascript generator node.js promise co
我试过下面的函数使用co和javascript promise测试,fulfill会成功返回但是reject没有,并且捕获错误未定义.并且流程无法继续.为什么?
错误:
> 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)
Run Code Online (Sandbox Code Playgroud)
码:
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); });
Run Code Online (Sandbox Code Playgroud)
捕获错误未定义
'error'不会.它会捕获错误,即您拒绝的价值.当然,它不是Error一个字符串,因此它没有.stack属性 - 这就是它记录的原因undefined.通过执行修复代码
reject(new Error('…'));
Run Code Online (Sandbox Code Playgroud)
另请参见Promise.reject消息是否应该包含在Error中?
流量无法继续.为什么?
好吧,因为你有一个错误,并抛出异常确实有这种行为.您还需要在错误处理程序中发送响应!
co(function *() {
…
}).catch(function onerror(error) {
console.error(error.stack);
res.send('err');
});
Run Code Online (Sandbox Code Playgroud)
或者如果您打算在通话时继续流程,请将.catch处理程序放在那里:
co(function *() {
yield testPromise().then(function(d) {
console.log(d);
}).catch(function(error) {
console.error(error.stack);
});
res.send('fin');
});
Run Code Online (Sandbox Code Playgroud)
或者,将您的promise调用包装在try-catch中:
co(function *() {
try {
var d = yield testPromise();
console.log(d);
} catch(error) {
console.error(error.stack);
}
res.send('fin');
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8779 次 |
| 最近记录: |