1

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?

Oboo Cheng
  • 4,250
  • 3
  • 24
  • 29
WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
  • you need to know that `async` functions always returning promises. are you sure that `rows` is returning an promise or the function when you call it like `query(...)`? – bill.gates Aug 12 '20 at 05:37
  • How then can the `pool.query` results be materialized? – WestCoastProjects Aug 12 '20 at 05:41
  • What does materialize means ? – Navitas28 Aug 12 '20 at 05:43
  • you mean resolve? if you write `let rows = await pool.query()` yo should be able to see some result with `console.log(rows)`. Down there i see you return the rows like `return rows`. Because its inside an `async function` this will be wrapped in an resolved promise you can think of this `return Promise.resolve(rows)`. You will need to access the values like this later `query(...).then(rows => console.log(rows))` – bill.gates Aug 12 '20 at 05:44
  • It's another way to say "computed immediately". I need the computation performed within the function and not postponed to the caller. – WestCoastProjects Aug 12 '20 at 05:44
  • @Ifaruki I do not understand: if `console.log(rows)` is able to show results immediately then why would it re-wrap as a `Promise` ? I do not want to invoke the `continuation` `.then()` inside the caller. – WestCoastProjects Aug 12 '20 at 05:46
  • `The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.` you can read here more https://javascript.info/async-await well the function itself is a promise so you are only able to get the results with `query.then(...)` or you make the function where your query should run also async so you need to write `await query(...)` – bill.gates Aug 12 '20 at 05:53
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – FZs Aug 12 '20 at 05:56

2 Answers2

3

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
}
Navitas28
  • 745
  • 4
  • 13
1

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');
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
  • Can you make this *return* a value? I need rows returned from the function and then not have to do a continuation in the main caller. I am getting a bit desperate and thinking to send in a Holder and place the results in the Holder. That's ugly but I don't have anything else working presently. – WestCoastProjects Aug 12 '20 at 05:57
  • check the value of rows, this async function returns the rows, you can handle that value inside the if block as you need. – sonEtLumiere Aug 12 '20 at 06:02
  • ok i'll try it out in about 20 mins: working through something else – WestCoastProjects Aug 12 '20 at 06:05
  • did not work. I ran in debugger and at the line `await pool.query(sql)` it jumps completely out of the `async function` with no data returned *and no error*. Just drives me crazy – WestCoastProjects Aug 12 '20 at 06:46
  • The `query('sql')` line returns a `Promise` and is not materialized. This answer is not a solution to the original question in its present form. – WestCoastProjects Aug 12 '20 at 06:55