Rahul Iyer
Rahul Iyer

Reputation: 21025

When using async await, how do you specify a callback?

I was looking at how to use transactions in:

https://node-postgres.com/features/transactions

But in the following code example:

const { Pool } = require('pg')
const pool = new Pool()

(async () => {
  // note: we don't try/catch this because if connecting throws an exception
  // we don't need to dispose of the client (it will be undefined)
  const client = await pool.connect()

  try {
    await client.query('BEGIN')
    const { rows } = await client.query('INSERT INTO users(name) VALUES($1) RETURNING id', ['brianc'])

    const insertPhotoText = 'INSERT INTO photos(user_id, photo_url) VALUES ($1, $2)'
    const insertPhotoValues = [res.rows[0].id, 's3.bucket.foo']
    await client.query(insertPhotoText, insertPhotoValues)
    await client.query('COMMIT')
  } catch (e) {
    await client.query('ROLLBACK')
    throw e
  } finally {
    client.release()
  }
})().catch(e => console.error(e.stack))

It seems that the function will execute immediately. Also there doesn't seem to be a way to specify a callback. Would it make sense to place the entire block from "(async()...." into a function, and then in the final statement before the end of the try block, add :

await callbackfunction();

Does that make sense? What would be a better way to add a callback function ?

Upvotes: 1

Views: 89

Answers (1)

Quentin
Quentin

Reputation: 943579

The point of await is that you don't use a callback. It returns the result of resolving the promise.

Without await:

do_something_asyc.then(function (data) { alert(data); });

With await:

var data = await do_something_asyc();
alert(data);

Upvotes: 2

Related Questions