Warm tip: This article is reproduced from serverfault.com, please click

Clientside javascript unpack value from asynchronous call

发布于 2020-12-26 16:42:46

I have the following code on my client server, connected to a node.js server:

async function updateHTML(text){
    const response = await ServerHandshake(text);
    console.log("done");
    let script = document.createElement("script");
    script.text = response;
    document.body.appendChild(script);
}


async function ServerHandshake(text){
    // POST
    fetch('/text', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            text: text
        })
    })
        .then(function(response){
            if(response.ok){
                console.log('POST success.');
                return;
            }
            throw new Error('POST failed.');
        })
        .catch(function(error){
            console.log(error);
        });

    // GET
    fetch('/processed', {method: 'GET'})
        .then(function(response){
            if(response.ok){
                console.log("GET success.");
                return response.json();
            }
            throw new Error('GET failed.');
        })
        .then(function(data){
            let returnValue = data.result;
            console.log(returnValue);
            return returnValue;
        })
        .catch(function(error) {
            console.log(error);
        });

}

(async function(){
    await updateHTML("hello, world!");
})();

The console logs the return value of serverHandshake, but the html file after the async call shows undefined.

"Done" is also printed first; it seems like that should be printed later, but somehow await is not properly working.

What's the properly way to do this?

Note I am asking about client-side, not server-side

Questioner
Alex Coleman
Viewed
0
Jeremy Thille 2020-12-27 00:48:43

You are mixing up callback-style (with .then()) and await-style, that's why it doesn't work.

Remove all .then() and use it this way :

async function updateHTML(text){
    const response = await ServerHandshake(text);
    
    if(response.ok){
        console.log('POST success.');
    }

}


function ServerHandshake(text){
    return fetch( ... ); // this can be awaited
}