In my current project, I am developing a custom render function for marked. This function is responsible for checking specific conditions on images, performing an asynchronous request, and ultimately returning an image from a different source. The challenge lies in the fact that the async request results in the return of a promise rather than a direct image URL.
The attachmentService.getBlobUrl
function plays a crucial role in this process. It is an asynchronous function that makes an HTTP request and returns a promise.
Here is a snippet of my render function implementation:
marked.use({
renderer: {
image: (src, title, text) => {
if (someCondition) {
// Parsing logic for the src attribute
// ...
return this.attachmentService.getBlobUrl(attachment)
.then(url => {
return Promise.resolve(`<img src="${url}" alt="${text}" title="${title}"/>`)
})
}
return `<img src="${src}" alt="${text}" title="${title}"/>`
},
}
})
I have attempted different approaches to handle the promise returned by the attachmentService.getBlobUrl
function. One option was to directly return the image tag within the promise chain:
// ...
return this.attachmentService.getBlobUrl(attachment)
.then(url => {
return `<img src="${url}" alt="${text}" title="${title}"/>`
})
// ...
An alternative attempt involved utilizing an async
wrapper without using Promise.resolve
:
// ...
return (async () => {
return await this.attachmentService.getBlobUrl(attachment)
.then(url => {
return `<img src="${url}" alt="${text}" title="${title}"/>`
})
})()
// ...
Both methods led to the same outcome - obtaining a promise instead of the desired result.
It is essential to note that using await
is not viable in this scenario due to the requirement for the render function to remain synchronous, which is beyond my control.