简体   繁体   English

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

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

I am trying to use a Sequelize promise inside of an existing async/await chain. 我正在尝试在现有的异步/等待链中使用Sequelize Promise。 Sequelize returns everything as a promise. Sequelize将一切作为承诺回报。 I am new to promises and async/await so I am using this as something of a learning experience. 我对promise和async / await不熟悉,因此我将其用作学习经验。 Please be extra patient with me. 请对我格外耐心。

My logic looks like this: 我的逻辑如下:

if row does not exist from previous '.then' 如果上一个'.then'不存在该行

create a new row and extract the new id 创建一个新行并提取新的ID

else 其他

extract id value from previous '.then' 从先前的'.then'提取ID值

So now I have a WORKING block of code now (below), from studying many excellent SO examples. 现在,通过研究许多出色的SO示例,现在(下面)我有了一个WORKING代码块。 I want to use all anonymous functions since IMHO it makes it a little bit easier to read. 我想使用所有匿名函数,因为恕我直言,它使它更易于阅读。 (yes debatable point, but for now I want to try getting this working with anonymous functions. (是值得商point的,但是现在我想尝试使用匿名函数来实现这一点。

It seems odd to have three nested return statements. 具有三个嵌套的return语句似乎很奇怪。 Is there a way to rewrite this block of code to be a bit cleaner but just using anonymous functions? 有没有一种方法可以重写此代码块,使其更整洁,但仅使用匿名函数?

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) => {

Thank you all. 谢谢你们。

Drop all the unnecessary IIFE , IIAFE , the return await and the Promise constructor antipattern : 删除所有不必要的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 are just values which can be await ed but you actually don't strictly need to await them, especially if your surrounding structure isn't using async / await . Promises只是可以await值,但是实际上您实际上并不需要严格地await它们,特别是如果您的周围结构未使用async / await You could write it like this: 您可以这样写:

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
        }
    })

If you return a Promise from within a .then() it will become part of the parent chain which is probably exactly what you want. 如果您从.then()内部返回一个Promise,则它将成为父链的一部分,而这恰恰是您想要的。

If you really want to use async / await , then I would recommend flipping the logic and doing the larger work after your happy path is accounted for like so: 如果您真的想使用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