-1

I'm trying to return the value of the first function, and use as variable on the second function, but it's showing this [object Promise].

addEventListener("fetch", event => {
  event.respondWith(fetchAndStream(event.request))
});

async function handleRequest(request) {
      var uri = request.url.replace(/^https:\/\/.*?\//gi, "/");
      return uri;
}

async function fetchAndStream() {

    uri = handleRequest();
    console.log(uri);
    // Fetch from origin server.
    let response = await fetch('http://blablabla.com/' + uri);

    const responseInit = {
        headers: {
            'Content-Type': 'application/octet-stream',
            'Content-Disposition': 'attachment; filename="file.m3u"',
        }
    };

    // ... and deliver our Response while that's running.
    return new Response(response.body, responseInit)
}
maik
  • 73
  • 4
  • 1
    `handleRequest` is `async`. Why? It doesn't do anything asynchronous. If you really want it to be async then `await` the result but also make sure it does an asynchronous operation. Otherwise, just don't have it as async. – VLAZ Jun 02 '22 at 05:03
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Samathingamajig Jun 02 '22 at 05:03

1 Answers1

1

You are calling your functions incorrectly without arguments. Your handleRequest takes an argument request in your function declaration

async function handleRequest(request) 

In your event listener you are calling the callback with an argument

fetchAndStream(event.request)

But you don't take any arguments here.

async function fetchAndStream() {

    uri = handleRequest();
    console.log(uri);

Since you have used your function handleRequest with async. It returns a promise wrapper which will await the execution, which I have doubts it will complete from there. The wrapper is like a placeholder which will be filled once your promise completes but since you are not calling the functions properly. Hence you are getting the output.

innocent
  • 864
  • 6
  • 17