Suppose I use node-mysql from npm to execute sql queries. With the advent of node 7 and the support of async / await, I would like to understand how you can apply this to perform sql queries? The task as a whole is to write a wrapper class for node-mysql so that later you can do something like:

let data = new MySqlWrapper().select(query); 

Well, in the end, in data we have the result of the query.

Tell me how you can implement this in this example:

 (async () => { let getData = async ()=> { db.query(`select * from users`,null,(err,data) =>{ console.log('ok'); return data; }); }; var res = await getData(); //нужно чтобы в res пришли данные запроса })(); 

    1 answer 1

    async/await constructs work fine not only with asynchronous functions, but also with Promises . For example, the code

     let select = function(query) { return new Promise(function(resolve, reject) { setTimeout(() => {resolve(`${query}s`)}, 1000); }); }; async function run() { let foos = await select('foo'); let bars = await select('bar'); console.log(`${foos} + ${bars}`); } run(); 

    displays the message foos + bars in two seconds.

    This little trick will allow you to solve your problem with "little blood". You can use one of the existing libraries to force your methods to return Promises . Let me give you an example of how this can be done using Bluebird :

     let bluebird = require('bluebird'), asyncWrapper = (f, ctx) => bluebird.promisify(f, {context: ctx}); let mysql = new MySql(); let data = await asyncWrapper(mysql.select, mysql)(query); 

    If you wish, you can write a class containing a new, asynchronous API. But this task is trivial and I will leave it for you :)

    • In your 1st example, assuming that after run(); at the very end there will be some code, then this code will not be executed until the run (2 seconds) run ? - sanu0074
    • @ sanu0074, no, but this should not happen. The await construct works only inside asynchronous functions (with an async token). Therefore, if you need to do something strictly in a row, put these commands in to run and supply their calls with the await marker - Dmitriy Simushev
    • @ sanu0074 We already discussed with you async/await right here . - Dmitriy Simushev
    • I read everything, and I don’t understand how to make this construction work, I gave an example in the question, can you tell me? - sanu0074
    • @ sanu0074 Rewrite all this horror inside the switch function so that it returns promis. An example of how with minimum effort to convert a function that takes a callback to a function that returns a promise I gave in the answer. - Dmitriy Simushev