简体   繁体   中英

Converting from Promise with .then() to async/await

I'm looking to better understand the idea of async/await to avoid having nested .then() database calls. The following code simplified code will work correctly, but I have some instances where I would like to make multiple database calls in a row.

var sql = require("sqlite3").verbose();
var db = new sql.Database('db.sqlite');

async function query(sql) {
    return new Promise((resolve, reject) => {
        db.all(sql, [], (err, rows) => {
            resolve(rows);
        });
    });
}

query('SELECT name FROM players')
    .then(rows => console.log("Players are: ", rows.map(p => p.name).join(", ")));

How do I convert this to use async/await in an elegant manor?

To convert a promise chain like:

query('SELECT name FROM players')
  .then(rows => console.log("Players are: ", rows.map(p => p.name).join(", ")));

Into async/await, you can do:

async function example() {
  const rows = await query('SELECT name FROM players');
  console.log("Players are: ", rows.map(p => p.name).join(", "));
}

Note: await ( currently ) can only be used within an async function, not globally.

var sql = require("sqlite3").verbose();
var db = new sql.Database('db.sqlite');


const query = async (sql) => {
    let response;
    await db.all(sql, [], (err,rows) => {
      response = rows;
    })
    return response;
}

const getRows = async () => {
   const rows = await query('SELECT name FROM players');
   console.log("Players are: ", rows.map(p => p.name).join(", ")));
}

getRows();

or


const query = async (sql) => {
    const [err, rows] = await db.all(sql, [])
    return [err, rows];
}

async can't be in the global scope

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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