同步调用和合并主体的结果是异步

时间:2016-02-10 05:10:58

标签: 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
    }]

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

现在看起来像这样:

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);
            }
        });
}

1 个答案:

答案 0 :(得分:-1)

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

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);
                }
            })