首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将视频标题作为变量存储在YTDL-核中?

将视频标题作为变量存储在YTDL-核中?
EN

Stack Overflow用户
提问于 2020-04-24 18:19:34
回答 1查看 302关注 0票数 0

如何将视频标题存储为全局变量?

代码语言:javascript
复制
ytdl.getBasicInfo(videoURL, function(err, info) {
  console.log(info.title)
});

我在这里看过其他问题/答案,但我似乎总是成功地打印标题来安慰,但无论我如何定义变量,它都是未定义的。

非常感谢你的帮助!

编辑:这是我正在尝试的当前方法,下面是从其他用户那里找到的一个例子:

代码语言:javascript
复制
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}`);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-25 02:21:29

getBasicInfo可以与回调或承诺一起使用。

使用回调:

代码语言:javascript
复制
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中使用承诺

代码语言:javascript
复制
ytdl.getBasicInfo(videoURL)
  .then(({title}) => {
    // same as above you can only use the title here
  })
  // log any error
  .catch(console.error);

({title}) => {...}也在破坏。

await中使用承诺(只能在异步函数中使用):

代码语言:javascript
复制
(async () => {
  try {
    const {title} = await ytdl.getBasicInfo(videoURL);
    // use title here
  } catch (err) {
    console.error(err);
  }
})();

解释

getBasicInfo是异步函数的一个例子。也就是说,它需要时间来执行(它需要在线获取视频信息)。

在ES2015 (ES6)之前,人们使用回调来处理异步函数。(有些人还使用了像蓝鸟这样的承诺库,但我不想在这里讨论这个问题。)回调函数将在异步函数完成或出现错误后执行。

例如,Node的require('http').get仍然使用回调:

代码语言:javascript
复制
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库的示例(取自自述):

代码语言:javascript
复制
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中,添加了承诺(以及箭头函数)。例如,您可以创建返回如下承诺的函数:

代码语言:javascript
复制
// 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)中,添加了awaitasync函数。await是另一种“解开”承诺的方法(暂停执行直到承诺得到解决)。await仅在已标记为async的函数中可用。

代码语言:javascript
复制
// 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的文章

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61414952

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档