javascript - 将 Sequelize promise 嵌入到 javascript async/await 链中

标签 javascript node.js promise async-await sequelize.js

我正在尝试在现有异步/等待链中使用 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/

相关文章:

javascript - 检查 div 内发生的链接点击

node.js - Cloud Functions for Firebase 错误处理

node.js - Nodejs 中的并发请求处理

node.js - 如何在 Node v10 的 Google Cloud Functions 中使用 ffi-napi

javascript - 在循环中链接 JavaScript Promise - bluebird

javascript - 在 node.js 中的 for 循环后完成多个 writeFile 函数时解决 promise

javascript - 将 Promise.all 与 easyPost API 结合使用来处理跟踪状态的多个请求

javascript - 使用数据库查找在 Node 中导出大文件 - 避免多次数据库调用?

javascript - Chart.js 条形图的值始终为 1 为什么我采用变量

javascript - 如何将 ui-grid 导出到 excel 文件?