【问题标题】:Does everything in a promise chain have to be a promise?承诺链中的所有内容都必须是承诺吗?
【发布时间】:2020-01-17 11:40:42
【问题描述】:

这是我实际代码的简化示例,但我试图确保它是有效的。我的问题是关于下面承诺链中的第二项。

// vars photo and image are declared outside of the promise chain

// ...
.then(() => Photo.create()) // this is a promise
.then(p => photo = p) // this is just assigning a variable, no promise
.then(() => image.resize({ height: 240 }).toBuffer()) // this is another promise
// ...

它有效,但这是处理这个问题的好方法吗?我这样组织它的原因是我基本上有一个中间步骤,我需要做一些分配和计算等,只是在组织上我想将它与我的其他 .then() 部分分开,这些部分是实际的承诺。

【问题讨论】:

  • 没有。你可以按照你正在做的方式去做,但是当没有异步发生时它没有多大意义。而是调用一个函数,并根据需要将该函数分成单独的函数。
  • 是或否,取决于您所说的“承诺链中的一切”是什么意思。

标签: javascript express promise sequelize.js chaining


【解决方案1】:

承诺链中的所有内容都必须是承诺吗?

嗯,你必须从链头的承诺开始,否则你没有一个 thenable 可以调用.then() on。

但是,除此之外,没有。 .then() 链中的项目不必使用承诺或返回承诺。您可以运行任何 Javascript。对于链中的下一个链接,重要的是来自 .then() 处理程序的返回值。

如果您的.then() 处理程序的返回值是一个普通值(不涉及承诺),那么该值将传递给下一个.then() 处理程序。

如果您的.then() 处理程序的返回值是一个promise,那么该promise 的解析值将被传递给下一个.then() 处理程序,并且promise 链在该promise 完成之前不会前进。


但是,如果链式 .then() 处理程序中没有任何异步内容,那么您可以将其与链的上一个或下一个链接结合起来,并消除简化事情的 .then() 处理程序。

例如这条链:

then(() => Photo.create()) // this is a promise
.then(p => photo = p) // this is just assigning a variable, no promise
.then(() => image.resize({ height: 240 }).toBuffer()) // this is another promise
// ...

可以简化为:

then(() => Photo.create()) // this is a promise
.then(p => {photo = p; return image.resize({ height: 240 }).toBuffer()}) // this is another promise
// ...

仅供参考,您在这里的具体示例甚至不需要链接,因为image.resize() 没有使用Photo.create() 的结果,所以除非这只是您编造一些要发布的代码的产物,那些两个操作可以并行运行,不必链接。 Promise 链适用于必须对操作进行排序的情况,通常一个步骤的输出是下一步输入的一部分。

【讨论】:

  • @Glenn - 这回答了你的问题吗?
猜你喜欢
  • 1970-01-01
  • 2016-01-10
  • 2018-08-05
  • 2021-02-04
  • 1970-01-01
  • 2022-11-06
  • 2017-04-26
  • 2018-06-23
相关资源
最近更新 更多