如果我们已经有了
const waitOneCycle = () => {
return new Promise(resolve => setTimeout(resolve));
};然后是我们的代码(这是目前在Jest和SinonJS中使用的,尽管它不一定是:)
waitOneCycle()
.then(() => {
// do something
});它读起来非常优雅:waitOneCycle和then做了一些事情。
但是,如果我们执行一系列操作,我们必须:
waitOneCycle()
.then(() => {
// do something
return waitOneCycle();
})
.then(() => {
// do something
return waitOneCycle();
})
.then(() => {
// do something
return waitOneCycle();
});它读起来很奇怪,因为我们为什么要返回一些东西来充当"waitOneCycle“呢?这是它的工作方式,但代码只是以一种奇怪的方式阅读。
我们可以这样做:
waitOneCycle()
.then(() => {
// not return anything here
})
.then(() => {
waitOneCycle()
.then(() => {
});
})但这将回到过去的嵌套地狱问题。有没有办法重构它,让它读起来连贯一致,同时所有动作都被序列化?
另外,在Ruby的例子中,如果promises是这样链接的,那么它实际上可以很好地读出,因为我们不需要使用return来计算最后一个值。所以它读起来像waitOneCycle,then,waitOneCycle,then...它看起来相当优雅。
发布于 2020-08-08 02:39:58
你不需要嵌套(而且只有当你return内在的承诺时它才会起作用),你也可以链接它:
waitOneCycle()
.then(() => {
// do something
})
.then(waitOneCycle)
.then(() => {
// do something
})
.then(waitOneCycle)
.then(() => {
// do something
})
.then(waitOneCycle);如果让waitOneCycle传递该值,这可能会工作得更好:
const waitOneCycle = (v) => {
return new Promise(resolve => setTimeout(resolve, v));
};当然,如果您希望promise代码能够连贯地读取并且没有嵌套(甚至连then回调都没有),那么就应该使用async/await语法。
https://stackoverflow.com/questions/63305779
复制相似问题