Goal of the code below is to replace some links with data fetched from API.
const articleData = '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor <a data-embed=\"Instagram\" href=\"https://www.instagram.com/p/CAttGmVIIAS/">incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in <a data-embed=\"Instagram\" href=\"https://www.instagram.com/p/CAttGmVIIAS/\">reprehenderit</a> in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>'
const article = document.createElement('div')
article.innerHTML = articleData;
[...article.querySelectorAll('[data-embed=Instagram]')].forEach(link => {
fetch(`https://api.instagram.com/oembed/?maxwidth=400&url=${link.href}`)
.then(response => {
if (response.ok) {
return response.json()
}
throw response.error
})
.then(json => {
const instagramHtml = document.createElement('div')
instagramHtml.innerHTML = json.html
console.log(link.parentNode)
link.parentNode.replaceChild(instagramHtml, link)
})
})
Everything works fine until it comes to replacing. It basically happens, but only within .then
method. How could I return from it?
Thank you!