如何将视频标题存储为全局变量?
ytdl.getBasicInfo(videoURL, function(err, info) {
console.log(info.title)
});我在这里看过其他问题/答案,但我似乎总是成功地打印标题来安慰,但无论我如何定义变量,它都是未定义的。
非常感谢你的帮助!
编辑:这是我正在尝试的当前方法,下面是从其他用户那里找到的一个例子:
var vidtitle;
function getTitleVideo (videoUrl){
return new Promise ((resolve, reject) => {
ytdl.getBasicInfo (videoUrl, (err, info) => {
resolve (info.title)
})
})
}
vidtitle = getTitleVideo(`https://www.youtube.com/watch?v=${youtube_video_id}`);发布于 2020-04-25 02:21:29
getBasicInfo可以与回调或承诺一起使用。
使用回调:
ytdl.getBasicInfo(videoURL, (err, info) => {
// log any error
if (err) return console.error(err);
const {title} = info;
/*
* you must put all your code that uses the title here
* if you try to make a global variable it may be undefined when you
* run the rest of the synchronous code
*/
});const {title} = info;是const title = info.title;的缩写。您可以阅读有关破坏这里的更多信息。
在then中使用承诺
ytdl.getBasicInfo(videoURL)
.then(({title}) => {
// same as above you can only use the title here
})
// log any error
.catch(console.error);({title}) => {...}也在破坏。
(async () => {
try {
const {title} = await ytdl.getBasicInfo(videoURL);
// use title here
} catch (err) {
console.error(err);
}
})();解释
getBasicInfo是异步函数的一个例子。也就是说,它需要时间来执行(它需要在线获取视频信息)。
在ES2015 (ES6)之前,人们使用回调来处理异步函数。(有些人还使用了像蓝鸟这样的承诺库,但我不想在这里讨论这个问题。)回调函数将在异步函数完成或出现错误后执行。
例如,Node的require('http').get仍然使用回调:
const {get} = require('http');
get('http://example.com', function (res) {
console.log(`The status code was ${res.statusCode}.`;
}).on('error', console.error);在本例中,回调不接受错误,而是get返回一个具有error事件的ClientRequest。
另一个使用不推荐的request库的示例(取自自述):
const request = require('request');
request('http://www.google.com', function (error, response, body) {
console.error('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});在ES2015中,添加了承诺(以及箭头函数)。例如,您可以创建返回如下承诺的函数:
// resolves after 500 ms
const doSomething = () => new Promise(resolve => setTimeout(resolve, 500));
// resolves with 'Hello, world!' after 500 ms
const getString = () =>
new Promise(resolve => setTimeout(resolve, 500, 'Hello, world!'));
// rejects with the error 'Error!' after 500 ms
const rejectingPromise = () =>
new Promise((resolve, reject) => setTimeout(reject, 500, new Error('Error!')))
// has a 50% chance to resolve and a 50% chance to reject
const mayReject = () => Math.random() > 0.5
? Promise.resolve('it worked!')
: Promise.reject(new Error("it didn't work"));
// using with then and catch
doSomething()
.then(() => {
console.log('done');
return getString();
})
.then(str => {
console.log(str);
return mayReject();
})
.then(str => {
console.log(str)
return rejectingPromise()
})
.catch(console.error);
您不必拒绝使用Error,但是这样做是很好的做法。
在ES2016 (ES7)中,添加了await和async函数。await是另一种“解开”承诺的方法(暂停执行直到承诺得到解决)。await仅在已标记为async的函数中可用。
// same stuff as before
const doSomething = () => new Promise(resolve => setTimeout(resolve, 500));
const getString = () => new Promise(resolve => setTimeout(resolve, 500, 'Hello, world!'));
const rejectingPromise = () => new Promise((resolve, reject) => setTimeout(reject, 500, new Error('Error!')));
const mayReject = () => Math.random() > 0.5 ? Promise.resolve('it worked!') : Promise.reject(new Error("it didn't work"));
// an async function
async function f() {}
// an async arrow function
const g = async () => {};
// an immediately invoked arrow function expression
// this does the same thing as the previous example with then/catch
(async () => {
try {
await doSomething();
console.log('done');
const str = await getString();
console.log(str);
// you don't have to assign it to a variable:
console.log(await mayReject());
await rejectingPromise();
} catch (err) {
console.error(err);
}
})();
我建议阅读MDN关于异步JS的文章。
https://stackoverflow.com/questions/61414952
复制相似问题