【问题标题】:Clientside javascript unpack value from asynchronous call客户端javascript从异步调用中解包值
【发布时间】:2024-04-26 16:35:02
【问题描述】:

我的客户端服务器上有以下代码,连接到 node.js 服务器:

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!");
})();

控制台记录了serverHandshake的返回值,但是异步调用后的html文件显示undefined

“完成”也最先打印;看起来应该稍后再打印,但不知何故 await 无法正常工作。

这样做的正确方法是什么?

注意我问的是客户端,而不是服务器端

【问题讨论】:

  • 您是否意识到您正在对/text 进行POST 和/processed 的GET 同时?如果您打算在 服务器从 POST 响应到 /text 之后完成 /processed 的 GET,那么您的 .then 的大括号在错误的位置,或者您应该等待您的获取.

标签: javascript http client-server


【解决方案1】:

您正在混淆回调样式(与.then())和等待样式,这就是它不起作用的原因。

删除所有.then()并以这种方式使用它:

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
}

【讨论】: