2017-12-02 114 views
0

我有一个函数可以进行数据库查询,然后需要返回结果。在返回值之前等待内部函数完成

查询是使用Node.js到mysql数据库,结果然后返回到询问者(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

+0

(如果你使用的节点或异步),你应该使用一个承诺或回调。 – Andy

+0

@Quentin为前端ajax调用提供了一个很好的资源:https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call。我认为这个问题有很大的不同,需要具体的答案。你会否将这个标记为重复? – Gerard

+0

这不是一个前端Ajax调用并不重要。这是一个异步调用,解决方案是相同的。 – Quentin

回答

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 
}) 
相关问题