Reputation: 664
every(60, 'seconds', function() {
var cron_channel = [];
session
.run('match (c:channel) where c.from="yt" return c')
.then(function(result){
result.records.forEach(function(record){
cron_channel.push({
title: record._fields[0].properties.channelid
});
console.log(cron_channel);
});
console.log(cron_channel);
});
when I execute this code than the above console.log prints the value but the below console.log prints undefined. help me how will I execute it complete session first and then console.log prints the value. I want the value outside the session. Thanks in Advance
Upvotes: 1
Views: 407
Reputation: 541
For executing codes sequentially in node js you can also use async.waterfall()
which is a function of npm async.
take reference from async
Upvotes: 3
Reputation: 3128
The way I always think about it is "Once you enter Promise-Land you can't escape". Whats happening is that Promises are functions that will run at some point in the future. When the above code runs it does the following:
.then()
)console.log
The thing is, since the value for cron_channel is fulfilled at some point in the future all your references to it need to be inside the promise chain.
If you elaborate on what you are trying to accomplish by having the value outside then there may be answers for that. My assumption is that you want to do more with the records after you have done your processing, If thats the case then you can keep chaining the .then
s until you finish what you need to. At some point you'll return the promise or call a callback. Thats how you will finish. e.g.:
every(60, 'seconds', function() {
var cron_channel = [];
session
.run('match (c:channel) where c.from="yt" return c')
.then(function(result){
result.records.forEach(function(record){
cron_channel.push({
title: record._fields[0].properties.channelid
});
console.log(cron_channel);
})
})
.then(function(){
console.log('the values are available here', cron_channel);
});
console.log(cron_channel);
});
Instead of using some out of scope variables, you can think of the promise chain as a pipeline.
every(60, 'seconds', function() {
session
.run('match (c:channel) where c.from="yt" return c')
.then(function(result){
return result.records.map(function(record){
return {
title: record._fields[0].properties.channelid
};
})
})
.then(function(cron_channel){
console.log('the values are available here', cron_channel);
});
});
Also, ES7's Async/Await can help with things like this. Values won't feel trapped inside Promises.
Upvotes: 0