Trouble getting promises instead of values from a function

I am trying to get a count of the number of callouts in a note. The function looks like this:

async function numCallouts(page) {
  const regex = />\s\[\!(\w+)\]\s(.+?)((\n>\s.*?)*)\n/  // callout
  const file = app.vault.getAbstractFileByPath(page.file.path)
  const contents = await app.vault.read(file)

  let count = 0
  for (const callout of contents.match(new RegExp(regex, 'sg')) || [] ) {
		count = count + 1
  }
   console.log(count)
   return count
}

Although I get the callouts count in the console.log, the dataview output shows only “Promises”. Like this:

versus the output in the console:
image

Would anybody know the right way of working with async, app.vault.read(file) and await inside a function?

Do you have await on the call to your function?

No, I didn’t.
But if I add it I get an error.
This is the call to the function:

dv.table(
	["Note"],
	pages
		.where(page => page.type == "paper")
		.sort(page => page.file.name, 'asc')
		.map(page => 
		 [
			page.file.link,
			await numCallouts(page)
			]
		)
)

The error looks like this:

Well, there is your problem. I’m running low on time, but you need to add a Promise.all() call around the query in order to properly await this function call. Examples are to be found within this forum.

The other option is to switch to a synchronized read variant, which would remove the need for awaiting at the expense of blocking output while the query runs.

1 Like

Thank you so much @holroy for providing me the clue to the solution.
Here is the working code:

async function numCallouts(page) {
   const regex = />\s\[\!(\w+)\]\s(.+?)((\n>\s.*?)*)\n/ 
   const file = app.vault.getAbstractFileByPath(page.file.path)
   const contents =  await app.vault.read(file)

   let count = 0
   for (const co of contents.match(new RegExp(regex, 'sg'))) {
	 count = count + 1
   }
   console.log(count)
   return count
}

dv.table(["Note", "NumCallouts"],
	await Promise.all(
		dv.pages('"Sources"')
			.where(page => page.type == "paper")
			.sort(page => page.file.name, 'asc')
			.map(async page => [
				await page.file.link,
				await numCallouts(page) ]
			 )
	  )
)

I am sure this can be done more elegantly.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.