【发布时间】:2019-12-30 23:06:42
【问题描述】:
我正在尝试在现有异步/等待链中使用 Sequelize 承诺。 Sequelize 将所有内容作为承诺返回。我对 promises 和 async/await 不熟悉 所以我把它当作一种学习经验。请对我多一些耐心。
我的逻辑是这样的:
如果前一个'.then'中的行不存在
创建一个新行并提取新的 id
否则
从之前的 '.then' 中提取 id 值
所以现在我有一个 WORKING 代码块(如下),来自研究了许多优秀的 SO 示例。我想使用所有匿名函数,因为恕我直言,它使它更容易阅读。 (是的,有争议的一点,但现在我想尝试使用匿名函数。
有 三个 嵌套的返回语句似乎很奇怪。有没有办法将这段代码重写为更简洁,但只使用匿名函数?
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) => {
谢谢大家。
【问题讨论】:
标签: javascript node.js promise async-await sequelize.js