Search code examples
node.jsfunctionasync-awaitdiscord.jsinstagram

How to get certain data from async function?


I'm trying to get data from the async function, however i'm unable to get it.

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);
      })()
    })
  })
})

response from .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]
    }
  },

I need to pick the shortcode from the response so i can somehow compare them, to detect if there was new post made and share it to the channel on discord..

console.log(res[0].shortcode); will return this...

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

ReferenceError: res is not defined

How i can receive just the shortcode so then i can somehow compare them to detect new post? (Not sure even how to do that heheh.. will be another research...)

Update from comments:

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

This won't return anything unfortunately.. not even first log.


Solution

  • Issues with your code

    Your code has two issues that stop it from functioning properly:

    1. You call upon the res variable after it has exited its scope.
    2. You attempt to get your res object's shortcode property erroneously.

    For issue number 1, there are a few ways to solve this, but the easiest would be to use a multi-line arrow function in order to keep the res variable in scope while you call console.log on it a second time.

    For issue number 2, saying console.log(res[0].shortcode); will most likely cause a type error to be thrown, as no property 0 exists on your res variable, so calling res[0] will return undefined. Trying to get a property from an undefined object will result in a TypeError. Based on the shape of the object you posted above, this should properly get the shortcode property from your res object:

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

    You can probably get this working by doing something like this:

    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);
                                })()
                        })
                    })
            })
    })
    

    Your usage of .then

    The objects returned by the function given to .then are wrapped in a Promise, which allows you to chain .then statements together. This allows for cleaner, less nested code. This can be utilized to clean up your code, like so:

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