I'm writing a configuration for the semantic-release tool using the release.config.js
file, which allows generating the configuration dynamically.
Now, I need to call several APIs during the loading process. I found that the best practice for calling APIs is to use fetch().then()
.
My code (simplified) is the following:
const config = {
plugins: [
// some plugins configurations here
]
}
if (/* some condition */) {
fetch(
// API1 URL and its params
).then((response) => response.json()).then((data) => {
return fetch(
// API2 URL and its params including `data.field`
)
}).then((response) => response.json()).then((data) => {
return data.another_field
}).then(function(value){
if (/* condition using the `value` */) {
// Prints correctly extracted `value` from the API2 call
console.log("Detected value", value)
config.plugins.push(/* Additional plugin */)
}
})
}
module.exports = config
The problem here is that in the end semantic-release
doesn't load that additional plugin.
I don't have enough experience with modern NodeJS, so I'm struggling to understand, how to force it to await
results from fetch
.
I found that in recent Node versions it's possible to use top-level await
, but simply adding await
before fetch
doesn't work for a reason that is unclear to me:
await fetch(
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
So, what is the best way to just perform a couple of synchronous API calls, or await results of all the fetch
es and then
s before the module.exports
?