从中间件中的承诺调用 'next()' 会导致“next shouldn't be called more than once”
Calling 'next()' from promises in a middleware causes 'next shouldn't be called more than once'
最近我将我的代码从 Express 更改为 Restify。老实说,我不确定以前是否曾经发生过,但我想确实发生过。
基本上在我的中间件中我调用了一个 promisified 方法,当它解析时我调用 next
并在下一个中间件中做其他事情。当它被拒绝时,我也想在某些情况下调用 next
而没有错误。否则它必须调用错误中间件将 err
传递给 next
.
somePromise()
.then(()=>{
next();
})
.catch((err)=>{
if(err.someatt) next();
else next(err)
});
它与 somePromise
的预期结果相得益彰。问题是 next
受 then-catch
链约束。当下一个中间件抛出错误时,它会调用 catch
方法并再次调用 next
!
我发现 next 有一个属性 called
,当我在再次调用 next 之前将其设置为 false 时,我摆脱了错误。但它当然是一种反模式。我在不同的中间件中遇到了同样的问题,我也使用了承诺(按预期调用 next
然后在 catch
语句中再次调用它)。
还有其他人遇到过这样的问题吗?
将您的链更改为:
somePromise().then(() => {
next();
}, err => {
// error occurred in somePromise()
if(err.someatt) next();
else next(err);
}).catch(err => {
// error occurred in .then()'s next()
// don't call next() again
});
.then()
的可选第二个参数充当 .catch()
回调,但仅针对链中更高层抛出的错误调用,不会针对相邻 [= 中抛出的错误调用11=]回调。
从 this awesome answer 借来的一个非常有用的流程图演示了 .then(onFulfilled, onRejected)
和 .then(onFulfilled).catch(onRejected)
之间的区别:
最近我将我的代码从 Express 更改为 Restify。老实说,我不确定以前是否曾经发生过,但我想确实发生过。
基本上在我的中间件中我调用了一个 promisified 方法,当它解析时我调用 next
并在下一个中间件中做其他事情。当它被拒绝时,我也想在某些情况下调用 next
而没有错误。否则它必须调用错误中间件将 err
传递给 next
.
somePromise()
.then(()=>{
next();
})
.catch((err)=>{
if(err.someatt) next();
else next(err)
});
它与 somePromise
的预期结果相得益彰。问题是 next
受 then-catch
链约束。当下一个中间件抛出错误时,它会调用 catch
方法并再次调用 next
!
我发现 next 有一个属性 called
,当我在再次调用 next 之前将其设置为 false 时,我摆脱了错误。但它当然是一种反模式。我在不同的中间件中遇到了同样的问题,我也使用了承诺(按预期调用 next
然后在 catch
语句中再次调用它)。
还有其他人遇到过这样的问题吗?
将您的链更改为:
somePromise().then(() => {
next();
}, err => {
// error occurred in somePromise()
if(err.someatt) next();
else next(err);
}).catch(err => {
// error occurred in .then()'s next()
// don't call next() again
});
.then()
的可选第二个参数充当 .catch()
回调,但仅针对链中更高层抛出的错误调用,不会针对相邻 [= 中抛出的错误调用11=]回调。
从 this awesome answer 借来的一个非常有用的流程图演示了 .then(onFulfilled, onRejected)
和 .then(onFulfilled).catch(onRejected)
之间的区别: