Javascript 承诺链中的一切都必须是承诺吗?

Javascript 承诺链中的一切都必须是承诺吗?,javascript,express,promise,sequelize.js,chaining,Javascript,Express,Promise,Sequelize.js,Chaining,这是我实际代码的一个简化示例,但我试图确保这是有效的。我的问题是关于下面承诺链中的第二项 // 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

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

// 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
// ...
这是可行的,但这是一个好办法吗?我这样组织它的原因是我基本上有一个中间步骤,我需要做一些作业和计算等,只是在组织上我想把它和我的其他部分分开。然后是实际承诺的部分

承诺链中的一切都必须是承诺吗

好吧,你必须从最前面的承诺开始,否则你就没有电话,然后继续

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

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

如果.then处理程序的返回值是一个承诺,则该承诺的解析值将传递给下一个.then处理程序和承诺链,直到该承诺得到履行

但是,如果链式.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的结果。因此,除非这只是您编写一些要发布的代码的产物,否则这两个操作可以并行运行,并且不必链接。承诺链适用于必须对操作进行排序的情况,通常一个步骤的输出是下一个步骤输入的一部分。

否。您可以按自己的方式执行,但在没有异步操作的情况下,这没有多大意义。改为调用一个函数,如果需要,可以将该函数拆分为多个函数。是或否取决于承诺链中所有内容的含义。@Glenn-这回答了你的问题吗?