我试图了解何时在嵌套 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/