在返回值之前等待内部函数完成

时间:2017-12-02 21:25:00

标签: javascript mysql node.js

我有一个进行数据库查询的函数,然后需要返回结果。

查询到mysql数据库,使用Node.js,然后将结果返回到Inquirer(NPM模块)提示符。

如果这是一个前端问题,我会使用jquery的内置承诺:(示例)。 $ .ajax.done()。但是,mysql NPM包没有用于query()方法的内置promise。

// OPTION 1, wait for query to complete before returning choicesArray (this example returns an empty array)

choices() {
  let choicesArray = [];
  connection.query(`SELECT * FROM products`, (err, res)=>{
    for (item of res) {
      choicesArray.push(`${item.product} | ${item.price}`);
    };
  });
  // wait here for query to complete
  return choicesArray;
}



// OPTION 2, change the syntax to take advantage of the query callback, something more like below (this example does not return the choicesArray all the way to the enclosing function)

choices() {
  connection.query(`SELECT * FROM products`, (err, res)=>{
    let choicesArray = [];
    for (item of res) {
      choicesArray.push(`${item.product} | ${item.price}`);
    };
    return choicesArray;
  });
} // (node:3877) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: You must provide a `choices` parameter

1 个答案:

答案 0 :(得分:1)

您无法从异步函数返回值。该函数在异步值准备就绪之前返回。你需要使用像:

这样的回调
function choices(cb) {
    let choicesArray = [];
    connection.query(`SELECT * FROM products`, (err, res)=>{
    if (err) {
        cb(err)
        return
    }
    for (item of res) {
        choicesArray.push(`${item.product} | ${item.price}`);
    };
    });
    // wait here for query to complete
    cb(null, choicesArray);
}

choices((err, value) =>{
    if (err) {
        // handle error
    } 
    // use value here
})

或者回复承诺:

function choices() {
    return new Promise((resolve, reject) => {
        connection.query(`SELECT * FROM products`, (err, res)=>{        
            if (err) return reject(err)
            let choicesArray = [];            
            for (item of res) {
                choicesArray.push(`${item.product} | ${item.price}`);
            }
            resolve(choicesArray)
        });

    })
}

choices()
.then(value => {
    // use value here
})
.catch(err =>{
    // handle error
})