首页 > 解决方案 > nodejs javascript承诺解决

问题描述

我似乎无法弄清楚如何保存SomeQuery承诺的结果。本质上,我想将值输入res并将其传递给parseQuery函数并返回最终结果。如何使 API 响应可以访问解析的结果。

const neo4j = require('neo4j-driver')
var parser = require('parse-neo4j')
const astria_queries = require('./astriaQueries')

const uri = 'bolt://astria_graph:7687'
const user = 'xxx'
const password = 'xxx'

const someQuery = (query) => {
  //   run statement in a transaction
  const driver = neo4j.driver(uri, neo4j.auth.basic(user, password))
  const session = driver.session({ defaultAccessMode: neo4j.session.READ })
  const tx = session.beginTransaction()

  tx.run(query)
    .then((res) => {
      // Everything is OK, the transaction will be committed
      parseQuery(res)
    })
    .then(() => {
      // Everything is OK, the transaction will be committed
    })
    .catch((e) => {
      // The transaction will be rolled back, now handle the error.
      console.log(e)
    })
    .finally(() => {
      session.close()
      driver.close()
    })
}

const parseQuery = (result) => {
  try {
    const test = parser.parse(result)
    console.log(test)
  } catch (err) {
    console.log(err)
  }
}

module.exports = {
  someQuery,
}

标签: javascriptnode.jsneo4jasync-awaites6-promise

解决方案


它终于和我合拍了。这是我想出的解决方案。希望它会帮助其他人。如果有更好的方法请告诉我。谢谢@fbiville 的帮助。

异步操作

const neo4j = require('neo4j-driver')
var parser = require('parse-neo4j')
const astria_queries = require('./astriaQueries')

const uri = 'bolt://astria_graph:7687'
const user = 'neo4j'
const password = 'neo'

async function getRecords(query) {
  //   run statement in a transaction
  const driver = neo4j.driver(uri, neo4j.auth.basic(user, password))
  const session = driver.session({ defaultAccessMode: neo4j.session.READ })
  const tx = session.beginTransaction()
  try {
    const records = await tx.run(query)
    const parseRecords = await parseQuery(records)
    return parseRecords
  } catch (error) {
    console.log(error)
  } finally {
    session.close()
    driver.close()
  }
}

async function parseQuery(result) {
  try {
    const parsedRes = await parser.parse(result)
    // console.log(parsedRes)
    return parsedRes
  } catch (err) {
    console.log(err)
  }
}

// getRecords(astria_queries.get_data_sources)

module.exports = {
  getRecords,
}

api 发送()

exports.get_data_sources = async (req, res) => {
  try {
    queryFuns.getRecords(astria_queries.get_data_sources).then((response) => {
      res.send(response)
    })
  } catch (error) {
    res.status(500).send(error)
    console.log(error)
  }
}

推荐阅读