Is afterInsert really after insert?

Hi everyone,
I’m using afterInsert hook to send a confirmation email upon submission to my website.
Basically, I’m calling afterInsert to create a new contact, grabbing its contactId and updating the same item to contain the contactId (see code below).
The problem is, once in a while the update fails because the item is not yet in the collection.
Is it even possible? I assumed that whatever happens in the afterInsert hook happens after the item was inserted…
Any ideas on how to make sure the item is already in my DB?
Attached is my code:

export function Credit_afterInsert(item, context) {
    console.log("Sending Confirmation email to: " + item.email);
    createContact(item);
 return item;
}

export function createContact(item) {
  wixCrmBackend.createContact({
 "firstName": item['email'],
 "emails": [item['email']]
 })
 .then((result) => {
 const contactId = result;
      item["contactId"] = contactId;
      wixData.update("Credit", item)
 .then( (results) => {
    console.log("Item updated successfuly. Email: " + item.email);
 } )
 .catch( (err) => {
    console.log("Couldn't update item: " + err + ". Email: " + item.email);
 } );
 }).catch((err) => console.log("Error while creating contact: " + err + ". Email: " + item.email));
}

This is the error I’m getting:

Error: WDE0073: Item [item] does not exist in collection [collectionName]

This is how I overcame the problem btw:

export async function Credit_beforeInsert(item, context) {
    item["affiliatesCount"] = 1;
    item.email = item.email.toLowerCase();
    item._id = item.email.toLowerCase();
    item.monthlySpending = parseInt(item.monthlySpending, 10);
 try{
      item.contactId = await wixCrmBackend.createContact({
 "firstName": item['email'],
 "emails": [item['email']]
 });
      console.log("Contact created successfuly. Email: " + item.email);
 } catch(error){
      console.log("Error while trying to create contact: " + error + ". Email: " + item.email);
 }
 return item;
}

I deleted the afterInsert hook and used await to store the contactId in the item in the beforeInsert hook.

Still interested to know why the error occurred in the first place though…

Guys, this issue has come up before a couple of times (to me too) and it drives you nuts, I know. Unless you know what’s happening. The problem is called “lag”. Wix has to distribute all changes thru its CDN and that takes a couple a millisecs. So the promise might be resolved, but that does not mean the distribution is finished.
I’ll give you the lowdown: wait for 250 ms between the create and the update and you’ll be fine.
Hope this helps.

Great, that explains a lot - thank you!
The fix I did should do the work too, right? (i.e. is there a lag in the create contact too)