How to chain a Promise within methods

I have the following code that does promise chaining but I want to chain the promise in methods for reusability. How can I do that? For instance below is an example

GetExistingCustomer(firstname, lastname, email)
    .then((results) => 
    {    
        if (result.status === "Successful") 
        {
          existingContactId = results.items[0].contactId;
          CreateNewContact(firstName, lastName, email).then((existingContactId) => {
            EmailContactByID(emailCode, existingContactId).then(() => {
              wixLocation.to("/Thankyoupage");
            })
          })
        }
        else
        {
          CreateNewContact(firstName, lastName, email).then((newcontactId) => {
             EmailContactByID(emailCode, existingContactId).then(() => {
                wixLocation.to("/Thankyoupage");
             })
          })
        }
    })

What I want to do is create a method called CreateNewContact but don’t know how to make the method so that it handles the promise.

GetExistingCustomer(firstname, lastname, email)
    .then((results) => {    
      if (result.status === "Successful") {
         existingContactId = results.items[0].contactId;
         CreateNewContactAndEmail(firstName, lastName, email, emailCode, existingContactId);
      }
     else {
         CreateNewContactAndEmail(firstName, lastName, email, emailCode, newcontactId);
     })
     
    
 export function CreateNewContactAndEmail(firstName, lastName, email, emailCode, contactId) {
     CreateNewContact(firstName, lastName, email).then((contactId) => {
        EmailContactByID(emailCode, contactId).then(() => {
           wixLocation.to("/Thankyoupage");
         })
 }

Please format your code and put it in a code block.
its hard to read it like that.

Formatted and update in code block.

@peterlandis I don’t see in your code where you declare the newContactId and the emailCode, + it’ll be more compact if you use the same function call for both cases, something like:

getExistingCustomer(firstname, lastname, email)
    .then(results => {
let contactId;
result.status === "Successful" ? contactId =  results.items[0].contactId : contactId = newcontactId; 
     return createNewContactAndEmail(firstName, lastName, email, emailCode,  contactId);
     });
}
     
    
 export function createNewContactAndEmail(firstName, lastName, email, emailCode, contactId) {
     CreateNewContact(firstName, lastName, email).then((contactId) => {
    EmailContactByID(emailCode, contactId).then(() => {
           wixLocation.to("/Thankyoupage");
         })
 }

By the way, I don’t really understand why you decided to create a new contact if the contact already exists.