【问题标题】:How to get certain data from async function?如何从异步函数中获取某些数据?
【发布时间】:2021-09-18 00:39:04
【问题描述】:

我正在尝试从异步函数中获取数据,但是我无法获取它。

client.on('ready', () => {
IGclient
.login()
.then((data1) => {
  console.log('Data1: ', data1)
  IGclient
    .getProfile()
    .then(() => {
      (async () => {
        await IGclient.getUserByUsername({ username: "worldstar" })
      .then(res => console.log('Media: ', res.edge_owner_to_timeline_media.edges)) // it returns an array of your user's medias.
      console.log(res[0].shortcode);
      })()
    })
  })
})

.then(res => console.log('Media: ', res.edge_owner_to_timeline_media.edges))回复

Media:  [
  {
    node: {
      __typename: 'GraphVideo',
      id: '2662044547635514500',
      shortcode: 'CTxe2l2FIyE',
      dimensions: [Object],
      display_url: 'https://instagram.fbts7-1.fna.fbcdn.net/v/t51.2885-15/e35/241737702_603358297699631_5052269439534742639_n.jpg?_nc_ht=instagram.fbts7-1.fna.fbcdn.net&_nc_cat=1&_nc_ohc=nCAjzZxBpX8AX8dIRn2&edm=ABfd0MgBAAAA&ccb=7-4&oh=68d55b1e54e94573e4a539c2dbd18688&oe=6141BC66&_nc_sid=7bff83',
      edge_media_to_tagged_user: [Object],
      fact_check_overall_rating: null,
      fact_check_information: null,
      gating_info: null,
      sharing_friction_info: [Object],
      media_overlay_info: null,
      media_preview: 'ABcqvg4CEE8gZ5J7f41TE5lbyicN1/z702GfMCux5XGT9Dz+lU1u08zfz8p46Zwev+fypW1C5svBxwx+nFFZ8l8cgLgiir0M9SpMJUUsoxHkZJHXP16ZqEzOUy2Cp4+YDJ7Z45AHbH61u3DCWGQdNv8A7KfX8KxokdpN8aK+R1fJUH15xk/mMnipL9CxDbJMPMZ9ufQcenfkZ+lFPe1l4aI7CB9eD/jRS+ZRoRRKDulPmMPX7o+i9P5mnAHPFQtVmHpSGEcIXOB1oq2lFID/2Q==',
      owner: [Object],
      is_video: true,
      has_upcoming_event: false,
      accessibility_caption: null,
      dash_info: [Object],
      has_audio: true,
      tracking_token: 'eyJ2ZXJzaW9uIjo1LCJwYXlsb2FkIjp7ImlzX2FuYWx5dGljc190cmFja2VkIjp0cnVlLCJ1dWlkIjoiOGU3NTM2OGY2NGVlNGE1YjkyZTE5OWM2NjlhYzY0ZWEyNjYyMDQ0NTQ3NjM1NTE0NTAwIiwic2VydmVyX3Rva2VuIjoiMTYzMTU2MjU0ODYzOHwyNjYyMDQ0NTQ3NjM1NTE0NTAwfDM1NjczOTU5MDN8ZDA4YTU1NmIzYzYxYzljYWFiMDlmZDg5ZmFlZmEwM2QwYmEwNWJiNzkxYjJjNTBmOWU5NzdlOTQzNTM2YmQ0YSJ9LCJzaWduYXR1cmUiOiIifQ==',
      video_url: 'https://instagram.fbts7-1.fna.fbcdn.net/v/t50.2886-16/241879045_655893848721915_3756581789983524987_n.mp4?_nc_ht=instagram.fbts7-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=MKV6lvykxUIAX8y1V2t&edm=ABfd0MgBAAAA&ccb=7-4&oe=61421A71&oh=5fd9789d322617de1064d5e1618ba214&_nc_sid=7bff83',
      video_view_count: 92970,
      edge_media_to_caption: [Object],
      edge_media_to_comment: [Object],
      comments_disabled: false,
      taken_at_timestamp: 1631560467,
      edge_liked_by: [Object],
      edge_media_preview_like: [Object],
      location: null,
      thumbnail_src: 'https://instagram.fbts7-1.fna.fbcdn.net/v/t51.2885-15/e35/c0.210.540.540a/241737702_603358297699631_5052269439534742639_n.jpg?_nc_ht=instagram.fbts7-1.fna.fbcdn.net&_nc_cat=1&_nc_ohc=nCAjzZxBpX8AX8dIRn2&edm=ABfd0MgBAAAA&ccb=7-4&oh=222d3ead453326c4392261439f345998&oe=6141AF70&_nc_sid=7bff83',
      thumbnail_resources: [Array],
      felix_profile_grid_crop: null,
      coauthor_producers: [],
      product_type: 'clips',
      clips_music_attribution_info: [Object]
    }
  },

我需要从回复中选择shortcode,这样我才能以某种方式比较它们,以检测是否发布了新帖子并将其分享到不和谐的频道..

console.log(res[0].shortcode); 将返回这个...

console.log(res[0].shortcode);
                  ^

ReferenceError: res is not defined

我怎样才能收到shortcode 这样我就可以通过某种方式比较它们以检测新帖子? (甚至不知道如何做到这一点呵呵……将是另一项研究……)

来自 cmets 的更新:

client.on('ready', () => {
IGclient
.login()
.then((data1) => {
  console.log('Data1: ', data1)
  IGclient
    .getProfile()
    .then(() => {
      (async () => {
        await IGclient.getUserByUsername({ username: "worldstar" })
        .then(res => { console.log('Media: ', res.edge_owner_to_timeline_media.edges);       
        console.log(res.edge_owner_to_timeline_media.edges.Media[0].node.shortcode); })
      })
    })
  })
})

不幸的是,这不会返回任何内容.. 甚至不是第一个日志。

【问题讨论】:

  • 如果console.log('Media: ', res.edge_owner_to_timeline_media.edges) 返回该对象,那么res.edge_owner_to_timeline_media.edges.Media[0].node.shortcode 应该会为您提供简码。
  • 不幸的是,这不起作用@Brian K
  • 此外,“res”超出了您调用它的范围。你的代码应该是这样的:.then(res => { console.log('Media: ', res.edge_owner_to_timeline_media.edges)); console.log(res.edge_owner_to_timeline_media.edges.Media[0].node.shortcode); })
  • 如果我在 => 之后添加 { 我无法关闭代码.. 它不会像看起来那样工作..

标签: node.js function async-await discord.js instagram


【解决方案1】:

您的代码存在问题

您的代码有两个问题使其无法正常运行:

  1. 您在 res 变量退出其范围后调用它。
  2. 您尝试错误地获取 res 对象的 shortcode 属性。

对于问题 1,有几种方法可以解决此问题,但最简单的方法是使用 multi-line arrow function 以便在您第二次调用 console.log 时将 res 变量保持在范围内.

对于问题 2,说 console.log(res[0].shortcode); 很可能会引发类型错误,因为 res 变量上不存在属性 0,因此调用 res[0] 将返回 undefined。尝试从undefined 对象获取属性将导致TypeError。根据您在上面发布的对象的形状,这应该从您的 res 对象中正确获取 shortcode 属性:

console.log(res.edge_owner_to_timeline_media.edges.Media[0].node.shortcode);

您可能可以通过执行以下操作来完成此工作:

client.on('ready', () => {
    IGclient
        .login()
        .then((data1) => {
            console.log('Data1: ', data1)
            IGclient
                .getProfile()
                .then(() => {
                    (async () => {
                        await IGclient.getUserByUsername({
                                username: "worldstar"
                            })
                            .then(res => {
                                console.log('Media: ', res.edge_owner_to_timeline_media.edges);
                                console.log(res.edge_owner_to_timeline_media.edges[0].node.shortcode);
                            })()
                    })
                })
        })
})

.then 的用法

.then 的函数返回的对象被包装在Promise 中,这允许您将.then 语句链接在一起。这允许更清洁、更少嵌套的代码。这可用于清理您的代码,如下所示:

client.on('ready', () => {
    IGclient
        .login()
        .then(data1 => {
            console.log('Data1: ', data1);
            return IGclient.getProfile();
        })
        .then(() =>
            IGclient.getUserByUsername({
                username: "worldstar"
            })
        ).then(res => {
            console.log('Media: ', res.edge_owner_to_timeline_media.edges);
            console.log(res.edge_owner_to_timeline_media.edges[0].node.shortcode);
        });
})

【讨论】:

  • 不幸的是,我的请求太多,所以我的 acc 似乎将被临时锁定(由于测试),一旦我尝试您的代码,我会通知您。谢谢你的回答!
  • @Brain K,我试过你的代码,但问题是一样的...... console.log(res.edge_owner_to_timeline_media.edges.Media[0].node.shortcode); ^ 类型错误:无法读取未定义的属性“0”
  • @RasmonT 您在问题中发布的 JSON 让我认为这是您的“res”对象的形状。试试这个,然后: res.edge_owner_to_timeline_media.edges[0].node.shortcode
  • @RasmonT 刚刚编辑了答案以显示新的“res”对象形状。
  • @Brain K 是的,成功了!谢谢...现在我将继续努力...非常感谢您的帮助!
猜你喜欢
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-07
  • 2019-07-03
  • 2021-08-27
  • 1970-01-01
  • 2021-10-03
相关资源
最近更新 更多