javascript - RETURN 如何应用在嵌套的 Promise 中

标签 javascript node.js neo4j promise

我试图了解何时在嵌套 Promise(在 JavaScript 中)中使用“RETURN session.run”与“session.run”。我已经看过两者的示例,但我没有遵循不同用法的逻辑。我有以下代码(伪)作为示例。我正在使用 Neo4j 作为我的数据库:

fn=function(data,callback)
{
session
.run(cypherquery)
.then function(result)
 {
  return session  //why a return here...the code seems to work without it!
   .run(anothercypherquery1)
   .then function(result)
     {
      for (var i=0; i<result.somearray.length;i++)
       {
        session  //why wouldn't I use a Return here? or should I?
        .run(anothercypherquery2)
         {}
         .then(function(result){})
         .catch(function(err){})
       }
     }
   .catch( function(){})
 }
.catch(function(){})
Return cb();
} 

每个 session 都依赖于前一个 session 才能继续,但不需要 cypherquery 的返回数据。该场景类似于创建具有关系的新记录,其中第一个密码检查记录是否已存在...第二个密码创建新记录...第三个密码在 for 循环中创建关系。我正在尝试确定执行此操作的最佳方法,为什么?任何帮助将不胜感激。

最佳答案

假设您的 for 循环收集独立的 Promise,那么您可以使用 Promise.all(),如下所示;

fn = function(data,callback){
      session.run(cypherquery)
             .then(function(result){
                     return session.run(anothercypherquery1);
                   })
             .then(function(result){
                     var promises = [];
                     for (var i=0; i<result.somearray.length;i++) promises[i] = session.run(anothercypherquery2);
                     return Promise.all(promises);
                   })
             .then(function(result){
                     callback(result);
                   })
             .catch(function(err){});
     };

关于javascript - RETURN 如何应用在嵌套的 Promise 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39671894/

相关文章:

php - 每次加载页面时更改元素的位置

javascript - 在 ReactJS 中将唯一的列表项附加到 DOM

node.js - 在 gulp.watch 中过滤文件的最佳方法?

java - 模拟返回模拟 : Mocking neo4j (database) objects for unit testing of domain logic

python - neo4j 向具有相似属性的节点添加关系

java - 无法查询 Neo4J 数据库并出现内存不足错误

javascript - 改变子组件的状态

javascript - 尝试使用 Eclipse 的 Chrome 调试器调试 NodeJ 时“无法获取调试选项卡”

python - 永远运行 Python 脚本,记录错误并在崩溃时重新启动

mysql - Node js(Express js)Mysql读取ECONNRESET错误