I'm attempting to
- Fetch GET my website (with node-fetch)
- Scrape it with Cheerio to get specific posts
- Fetch GET from my CMS (with node-fetch) to check if there's already a post with the same time
- If the check shows no duplicates, Fetch POST into my CMS
The problem I've run into though, is that I can console.log() the duplicate check result, but when I make a conditional with the result for the Fetch POST request, it always returns the check result as a Promise
I'm not sure how to correctly structure my async .then() calls to correctly check.
Code (edited for simplicity):
fetch('https://www.myblog.com/', { method: 'get' })
.then((res) => {
return res.text()
})
.then((data) => {
const $ = cheerio.load(data)
const siteHeading = $('.post-item')
siteHeading.each((index, element) => {
const title = $(element).find('.entry-title').text()
const desc = $(element).find('.entry-content').text()
const exists = fetch(
'https://mycms.com/api/articles?filters[title][$eq]=' +
title,
{
method: 'GET',
}
)
.then((response) => response.json())
.then((article) => article.data[0])
.then((exists) => {
if (exists) {
// ^exists always shows up as True, console.log(exists) shows Promise<pending>
fetch('https://api.broadband.money/api/news-articles', {
method: 'POST',
body: JSON.stringify({
data: {
title: title ? title : null,
desc: blurb ? blurb : null,
},
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
}
})
})
})