【发布时间】: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