简体   繁体   中英

Scope with callback function

I have part of an if statement below that does a few api calls to facebook and instagram. I am having trouble getting the 'instagram' part of this to push the data to an array... I am thinkig is a scope issue but not sure - Maybe you can tell me why I am getting nothing pushed into my array. The comments explain what happens. I cant get the instagram posts to push to the instaFormattedPosts array.

else if(responseData.fbData && responseData.fbData.instaId){
            //First Get Fb Posts - I push them into this array, 'fbFormattedPosts' then use thatlater to update state. This one works, fbPost object gets pushed forEach() fbPosts.data response. 
            let fbFormattedPosts = []
            response = await fetch(`https://graph.facebook.com/${fbDataTemp.pageId}/feed?access_token=${fbDataTemp.pageAccessTokenLong}`)
            let fbPosts = await response.json()
            fbPosts.data.forEach(post => {
                if(post.message){
                    let fbPostObject = {
                        type: 'text',
                        data: post.message,
                        link: `http://www.facebook.com/${post.id}`,
                        date: post.created_time,
                        postId: post.id,
                        rockOn: []
                    }
                    fbFormattedPosts.push(fbPostObject)
                }
            })

            //Get IG Media Ids - This returns a list of instagram id's. 
            let instaFormattedPosts = []
            response = await fetch(`https://graph.facebook.com/v7.0/${fbDataTemp.instaId}/media?access_token=${fbDataTemp.pageAccessTokenLong}`)
            let instaPosts = await response.json()

            //Get IG Posts - Alright here is where I cant get the instaPostObject to push to isntaFormattedPosts array...
            instaPosts.data.forEach(async instaId => {
                const instaResponse = await fetch(`https://graph.facebook.com/${instaId.id}?fields=id,media_url,timestamp,username&access_token=${fbDataTemp.pageAccessTokenLong}`)
                let instaPostRendered = await instaResponse.json()

                let instaPostObject = {
                    type: 'instagram',
                    data: instaPostRendered.media_url,
                    link: `http://www.instagram.com/${instaPostRendered.username}`,
                    date: instaPostRendered.timestamp,
                    postId: instaPostRendered.id,
                    rockOn: [],
                }
                instaFormattedPosts.push(instaPostObject)
                console.log(instaPostObject) //Returns the object with the right details.
            })

            console.log(instaFormattedPosts) // returns empty array.. 


            //Set All Posts 
            setPosts([ 
                ...responseData.posts, 
                ...fbFormattedPosts
                   .filter(({postId}) => 
                      !responseData.posts
                         .find(post => post.postId == postId)),
               ...instaFormattedPosts
             ])
        }

async await don't work with forEach , it will just invoke

// this will just loop through all the data inside and instaPosts
// and not wait to complete inside block

instaPosts.data.forEach(async instaId => {
    // your code
    instaFormattedPosts.push(instaPostObject)
    console.log(instaPostObject) //Returns the object with the right details.
})

Solution: is simple for loop

for (let i=0 ; i< instaPosts.data.length ; i++) {
    const instaId = instaPosts.data[i];
    const instaResponse = await fetch(`https://graph.facebook.com/${instaId.id}?fields=id,media_url,timestamp,username&access_token=${fbDataTemp.pageAccessTokenLong}`)
    let instaPostRendered = await instaResponse.json()

    let instaPostObject = {
        type: 'instagram',
        data: instaPostRendered.media_url,
        link: `http://www.instagram.com/${instaPostRendered.username}`,
        date: instaPostRendered.timestamp,
        postId: instaPostRendered.id,
        rockOn: [],
    }
    instaFormattedPosts.push(instaPostObject)
    console.log(instaPostObject) //Returns the object with the right details.
}
console.log(instaFormattedPosts) // <---- CHECK NOW

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM