我需要使用回调吗?

Do I need to use callbacks?

本文关键字:回调      更新时间:2023-09-26
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 回调简单示例 这有点帮助,但我仍然不清楚它是如何工作的。在过去的一个小时里,我一直在试图弄清楚如何使用回调来编写它。

此模块由以下方式调用:

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

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

请改用getVideoLength(youtube_parser) 。 这实际上传递了youtube_parser函数本身,以便稍后调用(即当getVideoLength完成时)。 不过,可能需要(error, url) youtube_parser的论据。

这是我想出的解决方案。我能做些什么来增强此代码吗?

谢谢你的帮助。

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

优酷.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;