Home > Back-end >  Passing async values from a function into a transporter
Passing async values from a function into a transporter

Time:12-29

My code:

 async function accessSecretVersion() {
  const [version1] = await client.accessSecretVersion({
    name: email,
  });
  const [version2] = await client.accessSecretVersion({
    name: pass,
  });

  let payload = {
    user: version1.payload.data.toString(),
    pass: version2.payload.data.toString()
  }
  return payload;
}


const mySecrets = accessSecretVersion();

const transporter = nodemailer.createTransport(mySecrets.then(function (result) {
  const emailEnd = result.user
  const passEnd = result.pass
  console.log(emailEnd) // check = getting email 
  console.log(passEnd) // check = getting password 

  return {
    emailEnd,
    passEnd
  };

}, {
  host: 'email host',
  port: port,
  auth: {
    user: emailEnd,
    pass: passEnd,
  },
}));

I'm trying to pass the values from 'emailEnd' to user: 'emailEnd' etc but as I expected, I get the error

'ReferenceError: emailEnd is not defined'

I am new to javascript, and I know this is probably a really long way of trying to achieve what I need to but I just can't get my head around passing the values from function to function.

Thanks for any help or direction in advance

CodePudding user response:

The second argument to mySecrets.then must be a function that handles errors, but it is an object literal {host: ...}. And this object literal refers to an undefined variable emailEnd (which is only a local variable in the function that is the first argument to mySecrets.then).

What you want is probably something like

async function init() {
  const transporter = await mySecrets.then(function (result) {
    return nodemailer.createTransport({
      host: 'email host',
      port: port,
      auth: {
        user: result.user,
        pass: result.pass
      }
    });
  });
  // Do something with transporter.
}

Note that the transporter assignment is an asynchronous statement, because mySecrets is already asynchronous. You therefore have to place the assignment statement in another async function, depending on what you want to do with the transporter.

  • Related