如何在节点js中的异步函数内顺序执行代码

时间:2017-05-15 05:30:05

标签: javascript node.js

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); 
});

当我执行此代码而不是上面的console.log打印值但下面的console.log打印未定义。 帮助我如何首先执行完整会话然后console.log打印值。我希望会议之外的价值。 在此先感谢

2 个答案:

答案 0 :(得分:2)

为了在节点js中顺序执行代码,您还可以使用async.waterfall()这是npm async的函数。 参考async

答案 1 :(得分:0)

我一直在想的方式是“一旦你进入Promise-Land就无法逃脱”。发生的事情是,Promises是将在未来的某个时刻运行的功能。当上面的代码运行时,它执行以下操作:

  1. 实例化cron_channel
  2. 运行查询
  3. 注册回调(.then()
  4. 执行上一次console.log
  5. 如果查询成功,则执行回调函数
  6. 循环并填充cron_channel
  7. 登录回调
  8. 问题是,由于cron_channel的值在未来的某个时刻得到满足,因此所有对它的引用都需要在promise链中。

    如果你通过将值放在外面来详细说明你想要完成什么,那么可能会有答案。我的假设是你想在完成处理之后对记录做更多的事情。如果是这样的话那么你可以继续链接.then直到你完成你需要的东西。在某些时候,您将返回承诺或致电回叫。多数民众赞成你将如何完成。 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); 
    });
    

    您可以将承诺链视为管道,而不是使用某些超出范围的变量。

    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);
      }); 
    });
    

    另外,ES7的Async / Await可以帮助解决这个问题。价值观不会被困在Promises内。