如何执行多个回调并返回结果数组?

时间:2015-07-16 09:38:54

标签: javascript node.js dropbox-js

我试图以JSON格式在Dropbox中获取一组图像URL。为了做到这一点,我写了以下函数:

router.get('/thumbnails', function(req, res, next){
var images = [];
var imagesCount = -1;
var isLoggedIn = !!req.user;
var dropboxClient = req.app.get('dropboxClient');
console.log(dropboxClient);
dropboxClient.authenticate({interactive: false}, function(error, client) {
    if (error) {
        console.log(error);
        return 0
    }
    if (dropboxClient.isAuthenticated()) {
        dropboxClient.readdir(dropboxConfig.folder, function(error, entries) {
            if (error) {
                console.log(error);
                return 0
            }
            imagesCount = entries.length;
            entries.forEach(function(entry){
                var path = dropboxConfig.folder + '/' + entry;
                dropboxClient.makeUrl(path, {download: true}, function(err, res){
                    if(err){
                        console.log(err);
                        return 0
                    }
                    //console.log(res.url);
                    images.push({url: res.url});
                    console.log("Processed " + images.length + "/" + imagesCount);
                    if(images.length == imagesCount){
                        console.log(images);
                        res.json(images);
                    }
                });

            });
        });
    }

});

});

在观察控制台输出后,我相信所有URL都被加载到数组中,但数据在地址http://.../thumbnails上不可用,过了一段时间,如果尝试在浏览器中加载数据,则返回ERR_EMPTY_RESPONSE。

有谁知道为什么函数不返回数据?

1 个答案:

答案 0 :(得分:2)

dropboxClient.makeUrl(path, {download: true}, function(err, dbc_res){
    if(err){
        console.log(err);
        return 0
    }

    //console.log(res.url);
    images.push({url: dbc_res.url});
    console.log("Processed " + images.length + "/" + imagesCount);
    if(images.length == imagesCount){
        console.log(images);
        //res come from dropboxClient, not router.get!!!
        res.json(images);
    }
});

问题是,在res.json,你回答dropboxClient,而不是用户,你需要在res重命名dropboxClient.makeUrl(path, {download: true}, function(err, res){,以便用户得到答案。