wtfaremyinitials / osa-imessage

Send and receive iMessages with nodejs
MIT License
324 stars 54 forks source link

NodeNoob - nameForHandle returns "[object Promise]" #22

Closed rydens closed 6 years ago

rydens commented 6 years ago

Okay, sorry to bother you (because this is probably stupidly obvious and I don't mean to clog your issues with questions about the intricacies of Node), but when I run this:

imessage.listen().on('message', (msg) => {
  if (msg) {
    console.log(`${imessage.nameForHandle(msg.handle)} said hi`)
  }
})

It logs [object Promise] said hi when I receive a message, but I would obviously like it to log Bob said hi. I can't figure it out, any help would be appreciated, thanks.

wtfaremyinitials commented 6 years ago

Hi! The reason you receive a Promise is because it osa-imessage has to read information out of a database, which takes a relatively long time (a few hundred milliseconds). For efficiency purposes, it immediately returns a value which represents the future result of that database call. This allows your program to resume doing other things during this time. In order to wait until the Promise is "resolved" (completed), you have two options.

modern async/await syntax (preferred):

imessage.listen().on('message', async (msg) => {
  if (msg) {
    console.log(`${await imessage.nameForHandle(msg.handle)} said hi`)
  }
})

or

a hand-written .then chain:

imessage.listen().on('message', (msg) => {
  if (msg) {
    imessage.nameForHandle(msg.handle).then(name => {
      console.log(`${name} said hi`)
    })    
  }
})

Cheers.

rydens commented 6 years ago

Ah, great, thank you!

This certainly works, and I'm excited to explore this. Thank you!