繁体   English   中英

将Sequelize Promise嵌入到javascript异步/等待链中

[英]Embedding a Sequelize promise into a javascript async/await chain

我正在尝试在现有的异步/等待链中使用Sequelize Promise。 Sequelize将一切作为承诺回报。 我对promise和async / await不熟悉,因此我将其用作学习经验。 请对我格外耐心。

我的逻辑如下:

如果上一个'.then'不存在该行

创建一个新行并提取新的ID

其他

从先前的'.then'提取ID值

现在,通过研究许多出色的SO示例,现在(下面)我有了一个WORKING代码块。 我想使用所有匿名函数,因为恕我直言,它使它更易于阅读。 (是值得商point的,但是现在我想尝试使用匿名函数来实现这一点。

具有三个嵌套的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) => {

谢谢你们。

删除所有不必要的IIFEIIAFEreturn awaitPromise构造函数反模式

if (!Array.isArray(data) || !data.length) {
    // if record does NOT exist
    const result = await myTable.create({ ........ });
    return result._id; // we had to create one, so we return the *NEW* _id value 
} else {
    return data[0]._id; // we found one, so we just return the pre-existing _id value
}

Promises只是可以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
    })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM