0

Let me explain my question in a better way:

I am building a TwitterBot that creates random images and tweets them.
To do so, I have two functions in a NodeJS application, one called createImage and another called tweetIt

createImage creates a PNG file.
tweetIt takes this image and, using the twitter API, tweets it.

So I have something like this:

function createImage(){
  //creates an image and saves it on disk
}

function tweetIt(){
  //takes the image from the disk and tweets it
}

I need to execute createImage() before tweetIt(), since the second function depends entirely on the result produced by the first.

createImage();
tweetIt();

But NodeJS executes them in parallel. How can I force one function to be completed before the execution of the second one? I tried some solutions I found here with callbacks and external packages but nothing worked. Someone here have any ideia of what I'm doing wrong? Thanks!

  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – MinusFour Nov 14 '16 at 02:37
  • Any reason why `tweetIt` can't just be invoked inside `createImage` once it has created an image? – Red Mercury Nov 14 '16 at 02:41
  • You need to show us the code for `createImage()` so we can advise how to synchronize with the timing of when it's done (assuming it has some async operations). – jfriend00 Nov 14 '16 at 02:42

1 Answers1

2

You can make createImage return a promise

function createImage(){
  return new Promise((resolve, reject) => {
    // create image then resolve promise.
    // ...
    resolve()
  })
}

function tweetIt() {
  //takes the image from the disk and tweets it
}

createImage().then(tweetIt)
Red Mercury
  • 3,971
  • 1
  • 26
  • 32