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
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
You could use an
async
function withfor...of
loops instead.forEach
is not designed to work withPromise
s.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.