如何使用async.series node.js将request.get的值传递给回调

时间:2017-01-06 11:31:31

标签: javascript node.js asynccallback

我想展示我的代码:

    request({url: API_URL}, function (error, response, body) {

    if (!error && response.statusCode == 200) {

        console.log("Items received with success.");
        var data = JSON.parse(body);

        // catch duration from video
        for(var list in data) {
            var item = data[list];

            async.series([
                function(callback){
                    console.log("I'm inside fileExists function");
                    var result = '';
                    request.get('http://tobeymotos.com.br/video.mp4', function (error, response, body) {
                        if (!error && response.statusCode == 200) {
                            var video = body;
                            console.log("File exists and is OK");
                            var result = true;
                            console.log("Valor da result", result);
                        }
                        else{
                            console.log("This file do not exists, check error: "+ error);
                            var result = "xixi";
                        }
                    });
                    // usar aqui
                    callback(null, result);
                },
                function(callback){
                    // catch video duration
                    file = "http://tobeymotos.com.br/video.mp4"; // used as e.g.
                    console.log("I'm inside getVideoDuration function");
                    getDuration(file).then(function (duration) {
                        console.log("Duração do vídeo: " +duration);
                        return duration;
                    });
                    callback(null, 'b');
                },
                function(callback){
                    // code c
                    callback(null, 'c');
                },
                function(callback){
                    // code d
                    callback(null, 'd');
            }],
            // optional callback
            function(err, results){
                console.log(results);
            }
            )

            return 0;           
        }
    } else {
        console.log("Error: "+error);
    }
});

我使用async.series按顺序执行某些functions,因为我依赖于第一个的结果,继续下一个。

你可以看到我有一个" request.get"在第一个function中,其中:

request.get('http://tobeymotos.com.br/video.mp4', function (error, response, body) {
                    if (!error && response.statusCode == 200) {
                        var video = body;
                        console.log("File exists and is OK");
                        var result = true;
                        console.log("Valor da result", result);
                    }
                    else{
                        console.log("This file do not exists, check error: "+ error);
                        var result = "xixi";
                    }
                });
                // usar aqui
                callback(null, result);

问题在于我无法在callback中调用结果,它只是没有" exit" request.get

一些帮助?

1 个答案:

答案 0 :(得分:0)

request({url: API_URL}, function (error, response, body) {

    if (!error && response.statusCode == 200) {

        console.log("Items received with success.");
        var data = JSON.parse(body);

        // catch duration from video
        for(var list in data) {
            var item = data[list];

            async.series([
                function(callback){
                    console.log("I'm inside fileExists function");
                    var result = '';
                    request.get('http://tobeymotos.com.br/video.mp4', function (error, response, body) {
                        if (!error && response.statusCode == 200) {
                            var video = body;
                            console.log("File exists and is OK");
                            var result = true;
                            console.log("Valor da result", result);
                            callback(null, result);
                        }
                        else{
                            console.log("This file do not exists, check error: "+ error);
                            var result = "xixi";
                            callback(null, result);
                        }
                    });
                    // usar aqui

                },
                function(callback){
                    // catch video duration
                    file = "http://tobeymotos.com.br/video.mp4"; // used as e.g.
                    console.log("I'm inside getVideoDuration function");
                    getDuration(file).then(function (duration) {
                        console.log("Duração do vídeo: " +duration);
                        return duration;
                    });
                    callback(null, 'b');
                },
                function(callback){
                    // code c
                    callback(null, 'c');
                },
                function(callback){
                    // code d
                    callback(null, 'd');
            }],
            // optional callback
            function(err, results){
                console.log(results);
            }
            )

            return 0;           
        }
    } else {
        console.log("Error: "+error);
    }
});

你的回调在request.get函数之外,由于Node JS的性质,这可能导致你的回调在请求返回之前调用。节点JS是非阻塞的,因此除非明确告知,否则不会等到执行下一个函数之前执行。将回调置于request.get响应函数内部将强制它等待请求返回,然后执行带有结果的回调