0

I am working on a Python dashboard with FastAPI and Javascript. I have created a POST call returning an URL in FastAPI, which I am trying to fetch with Javascript and pass to the player. The output of this POST call is JSON. I am trying to assign the value of a certain key to the laURL variable. The problem is that even though I am using await and async function, Javascript is not really waiting for resolving the response and the second function is executed before the completion of the laURL assignment.

async function fetchLicense(playbackURL) {
    try {
        let response = await fetch(apiURL, {
            method: "POST"
        });
        if (response.ok) {
            let result = await response.json();
            let laURL = JSON.parse(result).la_url;
            return await laURL;
        } else {
            console.log("POST Error: ", response);
        } 
    } catch (error){
        console.log("POST Error: ", error);
    }
}

And then I am using the returned value in another function:

function fetchSource(playbackURL) {
    let laURL = fetchLicense(playbackURL);
    const source = {
        dash: playbackURL,
        drm: {
            widevine: {
                LA_URL: laURL 
            },
            immediateLicenseRequest: true
        }
    };
    return source;

I have checked and tried a couple of different solutions, but nothing seems to be working.

This should be really something straightforward, but unfortunately, the solution isn't so obvious to me.

Georgi Stoyanov
  • 594
  • 1
  • 9
  • 26
  • Not been able to test this, but if you change the line `function fetchSource(playbackURL) {` to `async function fetchSource(playbackURL) {` and then change the line `let laURL = fetchLicense(playbackURL);` to `let laURL = await fetchLicense(playbackURL);` This should help you work it out? – Robin Webb Jul 20 '21 at 14:57

1 Answers1

1

Javascript async/await is just syntactic sugar for using Promises. fetchLicense hence returns a promise. You can use Promise.then(/* callback */) to specify what should happen when data is resolved.

If you're unfamiliar with this, the following link might help you understand how it works exactly: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Peter
  • 171
  • 5