node.js - 同步调用和异步合并主体结果

标签 node.js express node-async node-request

这是 TheMovieDatabase 的结果

"results": [
    {
      "poster_path": "/k1QUCjNAkfRpWfm1dVJGUmVHzGv.jpg",
      "adult": false,
      "overview": "Based upon Marvel Comics’ most unconventional anti-hero, DEADPOOL tells the origin story of former Special Forces operative turned mercenary Wade Wilson, who after being subjected to a rogue experiment that leaves him with accelerated healing powers, adopts the alter ego Deadpool. Armed with his new abilities and a dark, twisted sense of humor, Deadpool hunts down the man who nearly destroyed his life.",
      "release_date": "2016-02-09",
      "genre_ids": [
        35,
        12,
        28,
        878
      ],
      "id": 293660,
      "original_title": "Deadpool",
      "original_language": "en",
      "title": "Deadpool",
      "backdrop_path": "/n1y094tVDFATSzkTnFxoGZ1qNsG.jpg",
      "popularity": 43.515295,
      "vote_count": 192,
      "video": false,
      "vote_average": 5.46
    }]

我还需要使用original_title 调用itunes api 并合并数组中每个对象的属性。如果我在属性名称上发生冲突,我不介意。

现在看起来是这样的:

request({
        uri: url,
        method: 'GET'
    },
    function (error, response, body) {
        // The movie Database results
        previousBody = JSON.parse(body);

        if (!error && response.statusCode === 200) {
            resultBody = JSON.parse(body);
            async.each(resultBody.results, function (element, callback) {
                // ITunes api call
                request({
                    uri: searchEndPoint + qs.stringify({
                        term: element.original_title,
                        media: 'movie',
                        entity: 'movie',
                        limit: 1
                    }),
                    method: 'GET'
                }, function (error, response, body) {
                    if (!error && response.statusCode === 200) {
                        // I want to append to the results of item in 'element' and send it back in the res

                        res.write(JSON.stringify(_.extend(element, JSON.parse(body))));
                    } else {
                        errorCallback(res, error, response, body);
                    }
                });
                callback()
            });

        } else {
            errorCallback(res, error, response, body);
        }
    }
);

当所有 itunes 结果都已解析并添加到响应中时,我想发回结果。

编辑:新代码:

        var fullResults = [];
    request({
            uri: url,
            method: 'GET'
        },
        function (error, response, body) {
            if (!error && response.statusCode === 200) {
                var resultBody = JSON.parse(body);
                async.map(resultBody.results, function (element, callback) {
                        request({
                            uri: searchEndPoint + qs.stringify({
                                term: element.original_title,
                                media: 'movie',
                                entity: 'movie',
                                limit: 1
                            }),
                            method: 'GET'
                        }, function (error, response, body) {
                            if (!error && response.statusCode === 200) {
                                fullResults.push(JSON.stringify(_.extend(element, JSON.parse(body))));
                                callback();
                            } else {
                                errorCallback(res, error, response, body);
                            }
                        });
                    },
                    function (err) {
                        if (err) {
                            errorCallback(res, err, response, body);
                        } else {
                            resultBody.results = fullResults;
                            res.status(200).send(resultBody);
                        }
                    });

            } else {
                errorCallback(res, error, response, body);
            }
        });
}

最佳答案

试试这个。我使用了异步 map 功能

request({
            uri: url,
            method: 'GET'
        },
        function(error, response, body) {
            // The movie Database results
            previousBody = JSON.parse(body);

            if (!error && response.statusCode === 200) {
                resultBody = JSON.parse(body);
                async.map(resultBody.results.map(function(element) {
                        return function(callback) {
                            // ITunes api call
                            request({
                                uri: searchEndPoint + qs.stringify({
                                    term: element.original_title,
                                    media: 'movie',
                                    entity: 'movie',
                                    limit: 1
                                }),
                                method: 'GET'
                            }, function(error, response, body) {
                                if (!error && response.statusCode === 200) {
                                    // I want to append to the results of item in 'element' and send it back in the res

                                    res.write(JSON.stringify(_.extend(element, JSON.parse(body))));
                                    return callback({
                                        error: error,
                                        body: body,
                                        response: response
                                    });
                                } else {
                                    return callback();
                                }
                            });

                        }
                    }, function(err) {
                        return errorCallback( err.error, err.response, err.body);
                    });

                } else {
                    return errorCallback(res, error, response, body);
                }
            })

关于node.js - 同步调用和异步合并主体结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35307291/

相关文章:

node.js - 在 async.forEachSeries 中引入延迟

javascript - 如何摆脱 Connect 3.0 弃用警报?

node.js - pm2 创建了一个 "source"目录并将我的所有文件复制到其中,为什么?

javascript - 如何从 eBay 通知中获取数据

node.js - 如何从 ReactJS 应用程序向 SOAP 端点发出发布请求

javascript - 使用 Mocha 和 Express Rest API 进行单元测试

javascript - 表达和 Sequelize - 在同一路径中加载不相关的模型

node.js - Node js 避免金字塔厄运和内存同时增加

node.js - Superagent 在异步 waterfall 中移动响应回调位置

node.js - 使用消息选择器时使用 nodejs 订阅 ActiveMQ STOMP?