简体   繁体   中英

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 returns everything as a promise. I am new to promises and async/await so I am using this as something of a learning experience. Please be extra patient with me.

My logic looks like this:

if row does not exist from previous '.then'

create a new row and extract the new id

else

extract id value from previous '.then'

So now I have a WORKING block of code now (below), from studying many excellent SO examples. 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.

It seems odd to have three nested return statements. 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 :

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 . 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.

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:

yourTable.findAll({ /* ... */ })
    .then(async (data) => {
        if (data && data.length) return data[0]._id

        const result = await myTable.create({ /* ... */ })

        return result._id
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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