skip to Main Content

I am trying to post a thread using node.js
If I have any media attached to a tweet, I need to upload it and store the uploadedId which is in my case mediaId. I am getting the mediaId inside a forEach loop, if I want to use it inside the forEach the value is available. But, I want to store the id into an array and access it while calling another method that is outside the forEach loops.

Below is the code I tried,

var tweets = post['thread'] 
tweets.forEach((tweet,index)=>{
    if(tweet['media']!=undefined){
        var files = tweet['media']['media_ids'] //Initially I stored the filenames in media_ids Array, later I am updating it with MediaId
        tweets[index]['media']['media_ids'] = []
        files.forEach(async(file)=>{
            var file = './public/images/'+files[0]
            const mediaId = await tClient.v1.uploadMedia(file);
            tweets[index]['media']['media_ids'].push(mediaId)
            console.log(tweets[index][media]['media_ids]) //Output: ['123456789'] This is the output I need.
        })
     }
})
console.log(tweets[0]['media']['media_ids']) //Output: [] This is the output I am getting.

I hope my problem is clear to you, please help me!

3

Answers


  1. The array.forEach does not wait to move to the next iteration after each async code execution is completed, instead for this context use for-in or Where loops

    Login or Signup to reply.
  2. You could use an async function with for...of loops instead. forEach is not designed to work with Promises.

    async function doSomething() {
        const tweets = post.thread;
        for (const [index, tweet] of tweets.entries()) {
            if (tweet.media != null) {
                tweets[index].media.media_ids = [];
                // Promise.all with Array#map could also be used here
                for (let file of tweet.media.media_ids) {
                    file = './public/images/' + file; 
                    // assuming you meant to use the current file, not always the first file
                    const mediaId = await tClient.v1.uploadMedia(file);
                    tweets[index].media.media_ids.push(mediaId);
                }
            }
        }
    }
    
    Login or Signup to reply.
  3. var tweets = post['thread'] 
    tweets.forEach((tweet,index)=>{
    if(tweet['media']!=undefined){
        var files = tweet['media']['media_ids']
        tweets[index]['media']['media_ids'] = []
        Promise.all(files.map(async file =>{
            var file = './public/images/'+files[0]
            const mediaId = await tClient.v1.uploadMedia(file);
            tweets[index]['media']['media_ids'].push(mediaId)
            console.log(tweets[index][media]['media_ids']) 
        }))
     }
    })
    console.log(tweets[0]['media']['media_ids'])
    

    You can use the Promise.all() method to ensure that all the asynchronous operations in your code are completed before proceeding with any further operations. The Promise.all() method takes an array of promises as its argument and returns a single promise that resolves when all the promises in the array are resolved. In your case, you can use the Promise.all() method to wait for the uploadMedia() operations to complete before logging the output of the tweets[0][‘media’][‘media_ids’] array.

    try this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search