0

I've tried to reduce my "problem" to be more concise. I'm trying to get back from an async function (the fetch must be in a specific function cause I'm doing other call in there).

testAsync is fired when a button is clicked :

async function testAsync(){
    console.log("start async");
    let result = await go(); // Waiting promise
    console.log("result "+result);
    alert(result);
}

Then I want to do the "go" thing

async function go(){
    fetch('https://apiurl.com', {
        method: 'POST',
        body: '{"URL":"anotherurltotest.com"}'
    })
    .then(response => response.json())
    .then(json => {return json;})
    .catch(err => {
        console.log(err)
    })
}

With this method : result is undefined and fired immediately, not awaiting the return json from then/fetch.

But I've tried this :

async function go(){
    return await fetch('https://apiurl.com', {
        method: 'POST',
        body: '{"URL":"anotherurltotest.com"}'
    })
    .then(response => response.json())
    .catch(err => {
        console.log(err)
    })
}

With this, the result are fired only after a short time and are populated.

Why is the return in the then not working ? but return awaiting all the fetch, yes ?

Thanks :)

Frackher
  • 11
  • 2
  • `function go() { fetch(...).then(...); }` — There's objectively no `return` statement in `go`. The `return` inside the `then` callback function doesn't return from `go`, it returns from the callback function to the caller of the callback function (some `then` internals). – deceze Feb 25 '21 at 09:46
  • Put another way, what if you wrote it like `function cb(json) { return json; } function go() { fetch(...).then(cb); }`? That's an equivalent implementation… – deceze Feb 25 '21 at 09:47
  • Thank you and thanks for the thread you linked. There is a lots of informations in there and I will read it carrefully. – Frackher Feb 25 '21 at 09:49

0 Answers0