I'm really struggling with the concept of a promise and how to access data returned by one. I am trying to access order information on a Thank You page in Wix. I am then trying to send that data to Facebook. You can see from the below which console.log's work and which do not. Suggestions please!
import wixLocation from 'wix-location';
import {postToFacebook} from 'backend/facebookModule.jsw';
import {hashData} from 'public/pages/masterPage.js';
import {getUserIP} from 'public/pages/masterPage.js';
$w.onReady(async function () {
$w('#thankYouPage1').getOrder()
.then((order) => {
const orderObj = order;
console.log('this works! '+ orderObj.number)
})
.catch((error) => {
console.log(error);
});
console.log('this DOES NOT work '+ orderObj.number)
const data = {
"data": [
{
"event_name": "Purchase",
"event_time": Math.floor(Date.now() / 1000),
"action_source": "website",
"event_source_url": wixLocation.url,
"user_data": {
"em": (await hashData(orderObj.BillingInfo.email)),
"client_ip_address": (await getUserIP()),
"client_user_agent": navigator.userAgent
},
"custom_data": {
"currency": orderObj.currency,
"value": orderObj.totals.total
}
}
]
};
console.log(orderObj.totals.total);
//console.log(await postToFacebook(data));
await postToFacebook(data);
});
The error is of course on my second console.log:
workerLogger.js:103 ReferenceError: orderObj is not defined
SOLUTION - You need await:
import wixLocation from 'wix-location';
import {postToFacebook} from 'backend/facebookModule.jsw';
import {hashData} from 'public/pages/masterPage.js';
import {getUserIP} from 'public/pages/masterPage.js';
$w.onReady(async function () {
try {
var orderObj = await $w('#thankYouPage1').getOrder();
} catch (error) {
console.log(error);
}
const data = {
"data": [
{
"event_name": "Purchase",
"event_time": Math.floor(Date.now() / 1000),
"action_source": "website",
"event_source_url": wixLocation.url,
"user_data": {
"em": (await hashData(await orderObj.billingInfo.email)),
"client_ip_address": (await getUserIP()),
"client_user_agent": navigator.userAgent
},
"custom_data": {
"currency": await orderObj.currency,
"value": await orderObj.totals.total
}
}
]
};
//console.log(orderObj.totals.total);
//console.log(await postToFacebook(data));
await postToFacebook(data);
});