Trying to use await with promise in my code here - how to?

问题: I've tried but failed in grasping clearly how javascript promises and await work! I somehow managed to cobble together a function that performs what I need in my node.js mi...

问题:

I've tried but failed in grasping clearly how javascript promises and await work! I somehow managed to cobble together a function that performs what I need in my node.js micro service, but I'm not sure if I'm doing it the right (optimal) way. Also, I achieved what I wanted using promise without await, but also I haven't done any extensive testing of my code to see if it is indeed running exactly the way I think it is. Here is my code that I currently have and works, but I'm not sure if I'm missing using await for proper functioning:

  const QryAllBooks = {
        type: new GraphQLList(BookType),
        args: {},
        resolve(){
              return new Promise((resolve, reject) => {
                 let sql = singleLineString`
                      select distinct t.bookid,t.bookname,t.country
                      from books_tbl t
                      where t.ship_status = 'Not Shipped'
                  `;
                 pool.query(sql, (err, results) => {
                   if(err){
                      reject(err);
                   }
                   resolve(results);

                const str = JSON.stringify(results);
                const json = JSON.parse(str);

                const promises = [];
                for (let p = 0; p < results.length; p++){
                   const book_id = json[p].bookid;
                   const query = `mutation updateShipping
                                  {updateShipping
                                   (id: ${book_id}, input:{
                                      status: "Shipped"
                                   })
                                   { bookid
                                     bookname }}`
                    promises.push(apolloFetch({ query }));
               }

              //I need an await function so that previous apolloFetch  
              //goes in sequence of bookid, one after the other

              Promise.all( promises ).then(( result) => {
                      errorLogger(27, 'Error', result);
                      })
                     .catch(( e ) => {
                         errorLogger( 29, 'Error', e );
                     )};
                      });
                });
            }
          };

       module.exports = {
              QryAllBooks,
              BookType
       };

回答1:

Avoid the Promise constructor antipattern - you should not be doing anything after the call to resolve inside the promise executor. Put all that stuff in a then callback on the new Promise:

resolve() {
    return new Promise((resolve, reject) => {
        let sql = singleLineString`
            select distinct t.bookid,t.bookname,t.country
            from books_tbl t
            where t.ship_status = 'Not Shipped'
        `;
        pool.query(sql, (err, results) => {
            if(err) reject(err);
            else resolve(results);
        });
    }).then(results => {
        const str = JSON.stringify(results);
        const json = JSON.parse(str);

        const promises = [];
        for (let p = 0; p < results.length; p++){
            const book_id = json[p].bookid;
            const query = `mutation updateShipping {
                updateShipping(id: ${book_id}, input:{
                    status: "Shipped"
                }) { bookid
                     bookname }
                }`;
            promises.push(apolloFetch({ query }));
        }
        return Promise.all(promises);
    }).then(result => {
        errorLogger(27, 'Result', result);
        return result;
    }, err => {
        errorLogger(29, 'Error', err);
        throw err;
    )};
}

You can now replace those then calls with await syntax. And also exchange the Promise.all for a sequential awaiting in the loop:

async resolve() {
    const results = await new Promise((resolve, reject) => {
//                  ^^^^^
        let sql = singleLineString`
            select distinct t.bookid,t.bookname,t.country
            from books_tbl t
            where t.ship_status = 'Not Shipped'
        `;
        pool.query(sql, (err, results) => {
            if(err) reject(err);
            else resolve(results);
        });
    });
    const promises = results.map(res => {
        const book_id = res.bookid;
        const query = `mutation updateShipping {
            updateShipping(id: ${book_id}, input:{
                status: "Shipped"
            }) { bookid
                 bookname }
            }`;
        return apolloFetch({ query });
    });
    return Promise.all(promises);
}

async resolve() {
    const results = await new Promise((resolve, reject) => {
//                  ^^^^^
        let sql = singleLineString`
            select distinct t.bookid,t.bookname,t.country
            from books_tbl t
            where t.ship_status = 'Not Shipped'
        `;
        pool.query(sql, (err, results) => {
            if(err) reject(err);
            else resolve(results);
        });
    });
    const fetches = [];
    for (let p = 0; p < results.length; p++){
        const book_id = results[p].bookid;
        const query = `mutation updateShipping {
            updateShipping(id: ${book_id}, input:{
                status: "Shipped"
            }) { bookid
                 bookname }
            }`;
        fetches.push(await apolloFetch({ query }));
//                   ^^^^^
    }
    return fetches;
}
  • 发表于 2019-02-26 00:48
  • 阅读 ( 199 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除