2013-11-02 66 views
0
getDbFiles(store, function(files){ 
require('ms-db').connect("DBname", function (db) { 
    db.collection('collectionName').find().toArray(function (err, data) { 
     console.log(data); 
     store = data; 
    }) 
}); 
     getCdnFiles(store, function(files1) { 

     });}); 

我想调用这个getDbFiles func make查询,其结果应该可以通过getCdnFiles()访问,但它显示错误'store'未定义。所以请帮助我,如何实现这一目标使用节点JS和回调...卡住nodejs回调

+0

理想的'store'没有被定义。那是你的整个代码吗? –

+0

没有那不是整个代码,我不知道如何实现这个.. –

+0

你必须把'getCdnFiles'放在创建'store'的回调中,以便'store'在那个时候存在。 – Ryan

回答

2

如果你想的getDbFiles的结果是由getCdnFiles访问您需要将呼叫转移到getCdnFiles到的db.collection

回调函数
getDbFiles(store, function(files){ 
    require('ms-db').connect("DBname", function (db) { 
    db.collection('collectionName').find().toArray(function (err, data) { 
     console.log(data); 
     store = data; 

     getCdnFiles(store, function(files1) { 

     }); 
    }); 
    }); 
}); 

您还可以使用async.waterfall来帮助最小化回调级别。

+1

@BhushanGoel这个答案应该被接受。 – Chev

+1

我只是几乎没有把'callback hell *'变成有组织的代码的例子'async.waterfall'。认为它可能是相关的,所以[在这里](https://gist.github.com/Chevex/7299157)。 – Chev