简体   繁体   English

如何在异步 function 中实现 Promise 的结果?

[英]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:我正在尝试运行查询并在 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.但是,这些rows实际上返回Promise - 而不是实际结果。 This is not making sense to me: then what is the await actually achieving in there ?这对我来说没有意义:那么await在那里实际实现了什么 And then - how can the result be computed and returned by this function?然后 - 这个 function 如何计算和返回结果?

async-await is just syntactic sugar over the promises in javascript. async-await只是 javascript 中承诺的语法糖。

So using await is sufficient you don't have to again wait for the result in the then block所以使用 await 就足够了,您不必再次等待 then 块中的结果

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. try catch 是处理异步等待函数的好主意。 This is an example with a promise function that resolves after 3 seconds, i hope this helps.这是一个 promise function 的示例,它在 3 秒后解决,我希望这会有所帮助。

 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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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