Say I have an array of objects like this:
var posts = [ { title: 'Yessss',
image: 'https://i.redd.it/23ltzgkgax601.jpg' },
{ title: 'Is 37% still a pass?',
image: 'https://i.imgur.com/78pdycg.png' },
{ title: 'The best feeling there is',
image: 'https://i.redd.it/z6ldk7wmjd101.jpg' },
{ title: 'I don\'t follow pornhub someone retweeted it ',
image: 'https://i.redd.it/vsrbwxj8qr9z.jpg' },
{ title: 'Amazing cheating method discovered',
image: 'http://imgur.com/rvYV93m' },
{ title: 'I hate when this happens.',
image: 'https://i.redd.it/yx39xt2piv501.jpg' }];
and a function, makeImgTweets(). It takes the text to be posted as argument. The path to the image file is hardcoded as I want to override them (don't want to keep them).
function makeImgTweet(text) {
var b64content = fs.readFileSync("./image.jpg", { encoding: 'base64' })
Twit.post('media/upload', { media_data: b64content }, function (err, data, response) {
// now we can assign alt text to the media, for use by screen readers and
// other text-based presentations and interpreters
var mediaIdStr = data.media_id_string
var altText = text
var meta_params = { media_id: mediaIdStr, alt_text: { text: altText } }
Twit.post('media/metadata/create', meta_params, function (err, data, response) {
if (!err) {
// now we can reference the media and post a tweet (media will attach to the tweet)
var params = { status: text, media_ids: [mediaIdStr] }
Twit.post('statuses/update', params, function (err, data, response) {
console.log(data)
})
} else {
console.log(err);
}
})
})
}
How do I loop through the objects in posts, download the image through the link, then call the makeImgTweet function only after the image is downloaded?
Pseudocode:
posts.forEach(post) {
download(post.image) // save to ./image.jpg
makeImgTweets(post.title); // only run after image is downloaded
}