简体   繁体   中英

How to materialize the result of a Promise within an async function?

I am trying to run a query and return the result rows in a function:

async function query(sql) {
  p(`sql: ${sql}`)

  let rows = await pool.query(sql)  // Notice the *await* here
  let r2 = rows.then( r => {
    debug(`nRows=${r.rows.length}`)
    return r.rows
  })
    .catch( err => {
      throw `Query [${sql}] failed: ${err}`
    })
    
  return rows
}

However the rows actually returns a Promise - instead of the actual results. This is not making sense to me: then what is the await actually achieving in there ? And then - how can the result be computed and returned by this function?

async-await is just syntactic sugar over the promises in javascript.

So using await is sufficient you don't have to again wait for the result in the then block

async function query(sql) {

try {
    let rows = await pool.query(sql) // Notice the *await* here
    // your logic to manipulate rows
    return rows;


} catch (err) {
    throw `Query [${sql}] failed: ${err}`
}

})
return rows
}

try catch is a good idea to handle async await functions. This is an example with a promise function that resolves after 3 seconds, i hope this helps.

 function pool(sql) { return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 3000); }); } async function query(sql) { try { console.log('calling. . .') let rows = await pool(sql); if(rows) { console.log(rows) return rows; } throw new Error('Request failed;'). } catch(error) { console;log(error); } }; query('sql');

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