It's the first time I use promises in JavaScript so I apologise in advance if this is a dumb question. I need to fetch a field from an API call and use it in another function. This is my code:
async function getComposerName() {
try {
let composerID = document.querySelectorAll('#addCompositionFromPerformanceForm select')[0].value
let url = 'http://151.236.37.122/api/profiles/' + composerID + '/?format=json';
let response = await fetch(url);
let composition = await response.json(); // read response body and parse as JSON
console.log(composition['user']); // This correctly returns the name of the composer in the console at the end of addComposition() is run.
let ComposerName = composition['user'] // this is a valid value when run in the browser's console
return ComposerName;
}
catch(error){
console.log('error')
}
}
function full_title(){
var title = document.querySelectorAll('#addCompositionFromPerformanceForm input')[1].value
let fullTitle = title + ', by ' + getComposerName()
return fullTitle;
}
function addComposition (oFormElement) {
if ( confirm("Are you sure you wish to add " + full_title() + " to the database?") == false ) {
return false ;
} else {
[other stuff]
When I call the addComposition()
function (it's a form submit) I get the alert message with this text:
Are you sure you wish to add My Title, by [object Promise] to the database?
Of course I'd like to see the composer's name instead of [object Promise]
. The funny thing is that when I click on 'cancel' I see the composer's name popping up in the console log, which means, I suppose, that the promise gets fulfilled after the whole code in addComposition()
is run. Am I right? How do I get the composer's name in my alert message?
Thanks.