【问题标题】:How to get neo4j query result returned from .then with node js如何使用node js从.then返回neo4j查询结果
【发布时间】:2020-09-04 18:34:59
【问题描述】:

我需要使用适用于 Node JS 的 Neo4j 驱动程序来获取返回的数据。我的问题是,我可以在 .then 调用 inside 的控制台上打印 'online' 的值,但我似乎无法在该部分之外访问它 - 我已尝试返回 @ 987654321@,将其分配给函数外部的预定义变量,但没有任何作用 - 例如,如果我尝试在此 sn-p 的最后一行打印online 的值,我得到的结果是Promise { <pending> }。我想我没有正确处理承诺,我查阅了很多教程和示例,但我无法解决。那么:我如何将返回的数据(record.get('onl')) 分配给var online 并获得实际结果而不是承诺? 在此先感谢:)

var online = session.run(cyp1, param).then(results => {
                return  results.records.map(record =>{
                    console.log(record.get('onl'))
                    return record.get('onl')                    
            })
            }).then(()=>{
                session.close()
        });
console.log(online)

【问题讨论】:

    标签: javascript node.js neo4j


    【解决方案1】:

    目前,您将 var online 分配为“承诺链”而不是“已解决的承诺”。您可以使用Async/Await 这将允许您以同步方式编写异步代码。

    async function getRecords(){
        const records = await session.run(cyp1, param);
    
        return records.map(record => record.get('onl'))
    }
    
    const online = await getRecords();
    

    使用 try/catch/finally

    try {
       const online = await getRecords();
    } catch (error) {
       // do something
    } finally {
       await session.close()
    }
    

    如果您想继续使用.then() 您需要使用“Promise Chaining”并传递“Down the Chain”值,这会导致复杂的“Callback”/“Promise Chain”地狱。

    session.run(cyp1, param).then(results => {
        return results.records.map(record => record.get('onl'))
    }).then((online)=> {
        console.log(online)
    }).catch(() => {
        // do something
    }).finally(() => {
        session.close()
    });
    

    【讨论】:

      猜你喜欢
      • 2020-06-20
      • 2015-07-15
      • 2019-04-14
      • 2016-04-15
      • 2020-02-03
      • 2021-11-10
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      相关资源
      最近更新 更多