简体   繁体   English

在node.js中使用ES6 Promise返回空响应

[英]Returning empty response using ES6 promise in node.js

how can I call a query using ES6 native promises in node.js. 如何在node.js中使用ES6本机promise调用查询。 Below is the code. 下面是代码。

let arr= [];
    conn.query('select * from table1', (err, b) => {
    for (let i = 0; i < b.length; i++) {
        console.log(b[i]["id"])
        let promiseGetData = new Promise((resolve, reject) => {
            conn.query('select * from table2 where id = ?', [b[i]["id"]], (err, ce) => {
                if (err) {
                    const response = {
                        statusCode: 500,
                        body: JSON.stringify({
                            message: err
                        }),
                    }
                    reject(response);
                } else {
                    if (ce.length != 0) {
                        resolve(ce);
                    }
                }
            });
        });

        promiseGetData .then((data) => {
            b[i]['data'] = data;
            arr.push(b[i])
        }).catch((err) => {
            console.log(err);
        });
    }
console.log(b)
    })

I see an empty response when i do console.log(b). 当我执行console.log(b)时,我看到一个空的响应。 I dont know if I have used a promise in correct way, I think for first query I should execute in the promise as well. 我不知道我是否以正确的方式使用了承诺,我认为对于第一个查询,我也应该在承诺中执行。 Any help is very much appreciated 很感谢任何形式的帮助

Wrapping an async callback-based function into a promise is called Promisifying . 将基于异步回调的函数包装到Promisifying被称为Promisifying

You can of course use a library for that, but basically what it does is : 您当然可以为此使用库,但是基本上它的作用是:

const queryAsPromise = function( ...args ) {
    return new Promise( function( resolve, reject ) {
       try { 
           conn.query(...args, function( error, result ) {
               if ( error ) { 
                   reject( error );
               } else {
                   resolve( result );
               }
           } ); 
       } catch( error ) {
           reject( error );
       }
    } )
} );

By doing this one time you will keep your code DRY and you can always use that promise for making queries now : 通过执行此操作一次,您将使代码保持DRY状态,并且始终可以立即使用该承诺进行查询:

queryAsPromise('select * from table1')
     .then( result => {
          return Promise.all(
              result.map( b => {
                 return queryAsPromise('select * from table2 where id = ?', b["id"])
                             .then( data => b["data"] = data )
              } )
          )
     )
     .catch( err => res.send(500) )
     .then( console.log )

You got empty response from console.log(b) because the promise from querying database aren't finished. 您从console.log(b)得到空响应,因为查询数据库的承诺尚未完成。 You have to wait all of them to finish before you can get the full result. 您必须等待所有步骤完成才能获得完整结果。

Sample: 样品:

let arr = [];
conn.query('select * from table1', (err, b) => {

  var promiseArr = [];

    for (let i = 0; i < b.length; i++) {
        let promiseGetData = new Promise((resolve, reject) => {
            conn.query('select * from table2 where id = ?', [b[i]["id"]], (err, ce) => {
                if (err) {
                    const response = {
                        statusCode: 500,
                        body: JSON.stringify({
                            message: err
                        }),
                    }
                    reject(response);
                } else {
                    if (ce.length != 0) {
                        resolve(ce);
                    }
                }
            });
        });

            promiseArr.push(promiseGetData);
    }

    Promise.all(promiseArr).then((resultArr) => {
        //resultArr is all the resolved value returned from the promise in promiseArr
        for (let i = 0; i < resultArr.length; i++) {
            b[i]['data'] = resultArr[i];
            arr.push(b[i]);
        }
    }).then(() => {
        console.log(arr);
    }).catch((err) => {
        //if any promise throw/reject with error, it will go here directly
            console.log(err);
    });
})

Edit: Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise 编辑:参考: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

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

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