我正在尝试在现有异步/等待链中使用 Sequelize promise 。 Sequelize 返回所有内容作为 promise 。我是 promises 和 async/await 的新手 所以我把它当作一种学习经验。请对我格外耐心。
我的逻辑是这样的:
if row does not exist from previous '.then'
create a new row and extract the new id
否则
extract id value from previous '.then'
现在我有了一个 WORKING 代码块(下面),这是通过研究许多优秀的 SO 示例获得的。我想使用所有匿名函数,因为恕我直言,它使它更容易阅读。 (是的,有争议的一点,但现在我想尝试使用匿名函数来实现这一点。
有三个 嵌套的return 语句似乎很奇怪。有没有一种方法可以重写这段代码使其更简洁但只使用匿名函数?
yourTable.findAll( {...})
.then( (data) => {
// more code
})
.then( (data) => {
// more code
})
.then( (data) => {
if ( !Array.isArray(data) || !data.length ) {
// if record does NOT exist
return (async function () {
return await
(function () {
return new Promise( resolve => {
myTable.create( { ........ }
).then( (result) => {
resolve(result._id);
})
})
})();
})()
/* we had to create one, so we return the *NEW* _id value */
} else {
/* we found one, so we just return the pre-existing _id value */
return data[0]._id ;
}
})
.then( (data) => {
// more code
})
.then( (data) => {
谢谢大家
最佳答案
Promise 只是可以await
的值,但实际上您并不严格需要 await
它们,尤其是当您的周围结构没有使用 async
/await
。你可以这样写:
yourTable.findAll({ /* ... */ })
.then((data) => {
if (!Array.isArray(data) || !data.length) {
// We need to create one, return the new ID
return myTable.create({ /* ... */ })
.then((result) => result._id)
} else {
// We found one, return the existing ID
return data[0]._id
}
})
如果您从 .then()
中返回一个 Promise,它将成为父链的一部分,这可能正是您想要的。
如果您真的想要使用async
/await
,那么我建议您翻转逻辑并在您的快乐路径之后做更大的工作是这样计算的:
yourTable.findAll({ /* ... */ })
.then(async (data) => {
if (data && data.length) return data[0]._id
const result = await myTable.create({ /* ... */ })
return result._id
})
关于javascript - 将 Sequelize promise 嵌入到 javascript async/await 链中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57663293/