Until today, I thought that await
and then
were 2 different ways to handle promises results.
I used nodemailer.createTestAccount
to do some e2e testing and I stumbled in this counter-intuitive behaviour.
This is what the below code does:
- I have 2 test functions: testA and testB (they should do the same exact thing)
- I call the 2 functions and I get some output
- testA seems to work properly returning different value every call
- testB seems to return always the same value
const nodemailer = require("nodemailer");
const testA = async () => {
nodemailer.createTestAccount().then(account => { console.log("testA:", account.user) })
nodemailer.createTestAccount().then(account => { console.log("testA:", account.user) })
nodemailer.createTestAccount().then(account => { console.log("testA:", account.user) })
}
const testB = async () => {
const test1 = await nodemailer.createTestAccount()
console.log("testB:", test1.user)
const test2 = await nodemailer.createTestAccount()
console.log("testB:", test2.user)
const test3 = await nodemailer.createTestAccount()
console.log("testB:", test3.user)
}
testA()
testB()
The result (hand sorted for readability):
testA: [email protected]
testA: [email protected]
testA: [email protected]
testB: [email protected]
testB: [email protected]
testB: [email protected]
Can someone explain me why is this happening?