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

时间:2016-11-24 19:30:29

标签: javascript node.js promise es6-promise

如何在node.js中使用ES6本机承诺调用查询。以下是代码。

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

当我执行console.log(b)时,我看到一个空响应。我不知道我是否以正确的方式使用了一个承诺,我认为对于第一个查询我也应该在承诺中执行。非常感谢任何帮助

2 个答案:

答案 0 :(得分:2)

将基于异步回调的函数包装到promise中称为Promisifying

你当然可以使用一个库,但基本上它的作用是:

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

通过执行此操作,您将保持代码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 )

答案 1 :(得分:0)

您从console.log(b)得到空响应,因为查询数据库的承诺未完成。你必须等待所有人完成才能获得完整的结果。

样品:

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

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