PostgreSQL事务助手的`for await`循环查询数组 [英] Array of queries for `for await` loop for postgresql transaction helper

查看:104
本文介绍了PostgreSQL事务助手的`for await`循环查询数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个事务处理函数,可以像这样简化它的操作(起作用):

I made a transaction function that simplifies this action for me like this (it working):

export async function transaction(queriesRaw) {
  let allResults = []

  const client = await pool.connect()

  try {
    await client.query('BEGIN')
    var queries = queriesRaw.map(q => {
      return client.query(q[0], q[1])
    })

    for await (const oneResult of queries) {
      allResults.push(oneResult)
    }
    await client.query('COMMIT')
  } catch (err) {
    await client.query('ROLLBACK')
  } finally {
    client.release()
    return allResults
  }
}

并执行以下交易:

let results = await transaction([
            ['UPDATE readers SET cookies=5 WHERE id=$1;', [1]],
            ['INSERT INTO rewards (id) VALUES ($1);', [3]]
          ])

事务应按数组索引顺序一次执行一个查询(因此回滚到previos值将正常工作)并以相同的顺序返回(有时我需要从某些查询返回值)

Transaction should do queries one at a time in array index sequence (so rollback to previos values will work correctly) and return in the same order (sometimes i need return values from some queries)

据我所知,它已经开始在map map功能中。在等待中,我只是等待它的结果,第二次查询可能会更快地完成previos。

As i understand it starts already in map map function. In for await i just wait for results of it and second query may complete faster that previos.

那么我该如何解决呢?

P.S。也许像new Promise()这样的地图是正确的方法吗?

P.S. Maybe something like new Promise() instead map is the rigth way?

推荐答案

如果我正确理解了,只需使用for循环正确的 await ,而不是回调样式循环。

If i got you correctly, Just use a for loop with proper await, instead of a callback style loop.

因此,您可以等待函数返回所有内容是按时间顺序执行的,经过一番思考,您可以轻松地添加一个revoke()函数之类的东西。

So you can wait with the function to return unil everything is chronologically executed, With some thinking, you can easily add aa revoke() function or something..


...
export async function transaction(queriesRaw) {
  let allResults = []

  const client = await pool.connect()

  try {
    await client.query('BEGIN')

    for(var i = 0; i < queriesRaw.length;i++) {
        var res = await client.query(queriesRaw[i][0], queriesRaw[i][1])
        allResults.push(res)
    }

    await client.query('COMMIT')
  } catch (err) {
    await client.query('ROLLBACK') 

    // do you maybe wanna errors to results to?
    // allResults.push(err)
  } finally {
    client.release()
    return allResults
  }
}



信息,



例如异步模块或类似的模块。因此,您不必考虑这样的事情。

Info,

Have a look at for example async module, or something similar. So you will not have to think about things like this.

这篇关于PostgreSQL事务助手的`for await`循环查询数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆