I need to make a post request so I’m using the fetch request below.
async function record(recording_url, options) {
const recording_outcome = await fetch (recording_url, options);
const outcome = await recording_outcome.json();
return outcome;
}
let outcome = record(recording_url, options);
let record_div = document.getElementById("record_creation");
let record_saved = document.createElement("p");
record_saved.innerText = result.outcome;
However I’ve found the it doesn’t wait and the rest of the script keeps running and when adding to the innertext it prints a promise object. Do I need to restructure this or is there a sensible way to make sure it waits for the result?
I did try adding a promise like in the example below but that didn’t work as expected.
outcome.then(function(result){
record_saved.innerText = result.outcome;
});
2
Answers
You are making your code unnecessarily complex. Instead try this simple approach.
Try this, it will work.
As Sjoertjuh mentioned, the following code snippet will give you the data returned from the promise:
I’m unsure of what you are trying to accomplish next though which may be causing some confusion? Are you trying to display this text on your page? If so, you will need to insert the created p tag somewhere in the DOM like so:
It would also help to put a console.log tracer inside your returned promise logic like this:
Open up your developer tools and inspect the result in your console log to make sure you are accessing the correct data.