我需要使用回调吗?

时间:2014-12-26 02:50:59

标签: javascript node.js callback

var yModule = require('youtube-node'),
    nodeYoutube = new yModule();

nodeYoutube.setKey("key");

module.exports.getVideoLength = function (vData){
    youTube.getById(vData, function (result) {
        return convertTime(result['items'][0]['contentDetails']['duration']);
    })
};

var convertTime = function (time){
    var reptms = /(?:(\d+)DT)?(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/;
    var days = "00", hours = "00", minutes = "00", seconds = "00", formattedTime;


    //if (reptms.test(time)) {
        var matches = reptms.exec(time);
        console.log(matches);
        if (matches[1]) days = String(matches[1]);
        if (matches[2]) hours = String(matches[2]);
        if (matches[3]) minutes = String(matches[3]);
        if (matches[4]) seconds = String(matches[4]);
        formattedTime = "[" + days + ":" + hours + ":" + minutes + ":" + seconds + "]";
        return formattedTime;
    //}
};

即使在阅读了一些有关它的内容之后,我仍在努力理解回调。 nodeJs callbacks simple example这有点帮助,但我仍然不清楚它是如何工作的。我花了一个小时的时间试图弄清楚如何用回调来写这个。

这个模块正在被调用:

 ytRetrieve.getVideoLength(youtube_parser(text))

youtube_parser的功能:

function youtube_parser(url){
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
    var match = url.match(regExp);
    //console.log(match);
    if (match&&match[7]){
        return match[7].split(" ")[0];
    }
}

2 个答案:

答案 0 :(得分:0)

您需要使用回调。您的代码youtube_parser(的问题在于您正在调用该函数。回调是一个作为参数传递的函数,以便稍后调用。如果调用该函数,则返回一个字符串。 getVideoLength期望函数作为参数,而不是字符串。

而是使用getVideoLength(youtube_parser)。这实际上传递了youtube_parser函数本身以便稍后调用(即getVideoLength完成时)。但youtube_parser的参数可能需要(error, url)

答案 1 :(得分:0)

这是我提出的解决方案。有什么我可以做的来增强这段代码吗?

感谢您的帮助。

<强> Main.js

var ytempRetrieve = require('./youtube'), ytRetrieve = new ytempRetrieve();

var ytRegex = /(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?/;


bot.addListener('message', function (from, to, text, message) {
    if (text.match(ytRegex)) {
        console.log(text);
        youtube_parser(text, to, ytRetrieve.getVideoLength)
    }
});

function youtube_parser(url, to, callback) {
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
    var match = url.match(regExp);
    //console.log(match);
    if (match && match[7]) {
        callback(match[7].split(" ")[0], function (res) {
            setTimeout(function () {
                bot.say(to, match[7].split(" ")[0] + " is " + res + " long.")
            }, 1500)
        });
    }
}

<强> youtube.js

var yModule = require('youtube-node'),
    nodeYoutube = new yModule(),
    apiKey = require('./config');


    var youtube = function () {
    var self = this;

    self.time = null;

    self.setAPIKey = function (key) {
        nodeYoutube.setKey(key);
    };

    apiKey.getAPIKey(self.setAPIKey);

    self.getVideoLength = function (vData, callback) {
        nodeYoutube.getById(vData, function (result) {
            callback(self.convertTime(result['items'][0]['contentDetails']['duration']));
        })
    };

    self.convertTime = function (time) {
        var reptms = /(?:(\d+)DT)?(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/;
        var days = 0, hours = 0, minutes = 0, seconds = 0, formattedTime;

        //if (reptms.test(time)) {
        var matches = reptms.exec(time);
        console.log(matches);
        if (matches[1]) days = Number(matches[1]);
        if (matches[2]) hours = Number(matches[2]);
        hours += days * 24;
        if (hours.toString().length === 1) {
            hours = "0" + hours
        }
        if (matches[3]) minutes = String(matches[3]);
        if (minutes.toString().length === 1) {
            minutes = "0" + minutes
        }
        if (matches[4]) seconds = String(matches[4]);
        if (seconds.toString().length === 1) {
            seconds = "0" + seconds
        }
        formattedTime = "[" + hours + ":" + minutes + ":" + seconds - 1 + "]";
        return (formattedTime);
        //}
    };

};

module.exports = youtube;