我正在使用以下代码从Neo4J数据库中检索数据:
function findSystems() {
var myarray = [];
session
.run('MATCH (i:something) WHERE i.aproperty = {nameParam} return i.name as aname LIMIT 100', {nameParam: 'TX'})
.subscribe({
onNext: function (record) {
// add a single record
myarray(record.get('aname');
},
onCompleted: function () {
console.log(myarray);
session.close();
},
onError: function (error) {
console.log(error);
session.close();
}
});
}
现在它将myarray数组打印到控制台onCompleted(),但我不明白如何从这个函数返回数组,以便在我的代码的其他部分使用它...如何正确返回MYARRAY?
具体案例是我有一个调用findSystems()的函数giveMeData(),我需要findSystems()将数组返回给第一个函数giveMeData()
答案 0 :(得分:1)
使用Bolt Javascript diver处理查询响应有两种方法:
subscribe
)then
和catch
)由于您希望同步获得结果,因此您应该使用then
和catch
。
[EDITED]
例如,此函数版本将返回一个promise,doIt
函数会对该promise进行then
调用,以便知道何时使用myarray
值。
function findSystems() {
var myarray = [];
return session
.run('MATCH (i:something) WHERE i.aproperty = {nameParam} return i.name as aname LIMIT 100', {nameParam: 'TX'})
.then(function (result) {
result.records.forEach(function (record) {
myarray.push(record.get('aname'));
});
console.log(myarray);
session.close();
return myarray;
})
.catch(function (error) {
console.log(error);
return null; // Return null if there is an error
});
}
function doIt() {
findSystems()
.then(function(arr) {
// Put your code here to use the value of arr.
});
}
答案 1 :(得分:0)
只是您无法从observable
返回值所以解决的一种方法是设置回调函数/函数 你需要那个结果值,把那个函数作为参数传递给 findSystems函数,该函数将调用您的回调函数 当值可用时。
第二种方法是设置事件发射器,当值为时触发事件 可用
您可以使用我建议作为第一个选项的回调方法:
function findSystems(callback) {
var myarray = [];
session
.run('MATCH (i:something) WHERE i.aproperty = {nameParam} return i.name as aname LIMIT 100', {nameParam: 'TX'})
.subscribe({
onNext: function (record) {
// add a single record
myarray(record.get('aname');
},
onCompleted: function () {
console.log(myarray);
callback(myarray);
session.close();
},
onError: function (error) {
console.log(error);
session.close();
}
});
}
function callback(myarray)
{
console.log(myarray);
}
findSystems(callback);