I am trying to execute some asynchronous JavaScript code from PowerShell and get the result. However, when using the node command in PowerShell, it seems to only return synchronous results.
My PowerShell script is as follows:
$hubspot_api_key = 'xxx'
$result = $(node hubspot.js $($hubspot_api_key) 'ci')
Write-Output 'Results:' $result
The main part of my hubspot.js file is as follows:
(async () => { return await getContacts(); })()
How can I get the results to return immediately? When I run this the PowerShell script continues to process before the hubspot.js results are returned.
I tried using the code below but this does not work either.
$someFunc = $(node hubspot.js $($hubspot_api_key) 'ci') $results = Start-Job -ScriptBlock $someFunc | wait-job | receive-job
Additional code from hubspot.js:
getContacts = async () => {
const emailFilter = `*bstdev${environment}*`
console.log('emailFilter', emailFilter);
const filter = { propertyName: 'email', operator: 'EQ', value: emailFilter }
const filterGroup = { filters: [filter] }
const sort = JSON.stringify({ propertyName: 'createdate', direction: 'DESCENDING' })
const query = 'test'
const properties = ['createdate', 'firstname', 'lastname']
const limit = 100
const after = 0
const contacts = [];
const publicObjectSearchRequest = {
filterGroups: [filterGroup],
sorts: [sort],
query,
properties,
limit,
after,
}
let result = await hubspotClient.crm.contacts.searchApi.doSearch(publicObjectSearchRequest);
if(result.results){
result.results.forEach((publicObject) => {
contacts.push(publicObject.properties);
})
while(result.paging){
publicObjectSearchRequest.after = result.paging.next.after;
await setAsyncTimeout(async() => {
result = await hubspotClient.crm.contacts.searchApi.doSearch(publicObjectSearchRequest);
if(result.results){
result.results.forEach((publicObject) => {
contacts.push(publicObject.properties);
})
}
}, 1000);
}
}
console.log('count', contacts.length);
return contacts;
}