使用异步等待时,如何指定回调?

问题描述:

我一直在寻找如何使用交易:使用异步等待时,如何指定回调?

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

但在下面的代码示例:

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

看来这个函数会立即执行。此外似乎没有指定回调的方法。难道是有意义的整个街区的地方“(异步()......”成一个函数,然后在try块结束前的最后陈述中,添加:

await callbackfunction(); 

是否让?。感觉这将是一个更好的方式来添加一个回调函数

+1

如果您使用承诺(这是'async/await'也在幕后使用),你不应该需要回调。 – robertklep

+0

难道你不能在'.catch(...'? – DavidDomain

+0

@DavidDomain'then'调用语义不同于“callback”调用语义(其中第一个参数代表可能的错误)之前添加'.then(callback) 。但是你可以做'.then(v => callback(null,v))。catch(callback)' – robertklep

的await的一点是,你不使用的回调,它返回解决承诺的结果

没有等待:

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

随着等待:

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