node.jsemailasynchronoussynchronousjimp

How to make everything happen in order (Node js)


I'm writing a program to get data from a CSV file, duplicate an image, print text (someone's name name from a CSV file) onto that image using Jimp, then send an email with the image as the attachment to the email (the email is found in the CSV file), delete the image, then repeat.

The problem I get: everything is happening in the wrong order! I logged all the events, and it looks like this in the console:

Duplicate sucessful!
Duplicate sucessful!
[Function: send]
Hint: hit control+c anytime to enter REPL.
Email sent: 250 2.0.0 OK  1616631705 k17sm3426218pfa.68 - gsmtp
Email sent: 250 2.0.0 OK  1616631705 y68sm4040117pgy.5 - gsmtp
Draw successful!
Draw successful!
File deleted!
Error: ENOENT: no such file or directory, unlink 't.png'
    at Object.unlinkSync (fs.js:1136:3)
    at Timeout._onTimeout (/home/runner/TestWriting/index.js:82:10)
    at listOnTimeout (internal/timers.js:554:17)
    at processTimers (internal/timers.js:497:7) {
  errno: -2,
  syscall: 'unlink',
  code: 'ENOENT',
  path: 't.png'
}

t.png is the picture I'm duplicating. Meanwhile, when I get the emails, there's nothing printed on the image attachments! Here's some pseudocode to illustrate what my js file looks like:

load csv information
loop:
   duplicate image from another image
   print text onto image
   send email
   delete duplicated image
end loop

I've lined my code with tons of timeouts, and all it does is get more messed up. It worked (with some timeouts) without the loop, but once I added that, everything was messed. I have a hard time understanding all the tutorials online.

I'm relatively new to Node.js, so could someone help me out?

Any help is greatly appreciated!


Solution

  • I ended up using DeAsync with booleans to confirm when a process was finished. The process worked perfectly:

    Duplicate sucessful!
    Draw successful!
    Email sent: 250 2.0.0 OK  1616636784 p17sm3690310pfn.62 - gsmtp
    File deleted!
    Duplicate sucessful!
    Draw successful!
    Email sent: 250 2.0.0 OK  1616636792 s22sm3529891pjs.42 - gsmtp
    File deleted!
    

    In detail, I declared a couple of booleans on the top of the page, then once a process was finished, the boolean was declared true. To keep the program from going off, this is where DeAsync comes in:

    while(!duDone) require('deasync').runLoopOnce();
    

    Where duDone is the variable declared true once a process was complete.