【发布时间】:2015-06-06 03:41:59
【问题描述】:
我最近开始使用 NodeJS 和 MongoDB(使用 Monk)。这是我遇到“回调地狱”一词的时候。在我的代码中,我正在做同样的事情。举个例子-
DBCall(d1, function(e, docs){
if(docs.length!=0)
DBCall(d2, function(e, docs1){
if(docs1.length!=0)
DBCall(d3, function(e, docs2){
//doing something with docs,docs1,docs2
})
})
})
这是我开始阅读“承诺”的时候,我偶然发现了这篇文章 - https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/
由于我在第三个回调中同时需要 docs 和 docs1,所以我使用了嵌套的 Promise。
DBCall(d1)
.then(function(docs){
if(docs.length!=0)
return DBCall(d2)
.then(function(docs1){
if(docs1.length!=0)
return DBCall(d3)
.then(function(docs2){
//doing something with docs,docs1,docs2
})
})
})
从上面的代码 sn-p 我有以下问题(/疑问):
- 除了使代码更具可读性之外,Promise 是否具有性能优势?
- 嵌套承诺和回调地狱看起来与我相似。真的有区别吗?
我不熟悉这种承诺的概念。任何帮助表示赞赏。
【问题讨论】:
-
从技术上讲,您的嵌套承诺仍在使用回调,从而再次创建“回调地狱”。这次有更多代码。
-
那么,如果我使用 Promise 并且如果我想使用 docs,docs1,docs2 ,有没有办法避免回调地狱?
-
@User - 看看我更新的答案中的一些链接。
标签: javascript node.js callback