gpt4 book ai didi

javascript - 异步 POST 到数据库时出现问题

转载 作者:行者123 更新时间:2023-12-02 23:41:45 24 4
gpt4 key购买 nike

目前我有以下代码,基本上将表单的结果发布到数据库中,但有时表单中的某些字段可能为空,所以我被迫在更新之前检查对象并按顺序保存变量让它们不会变成空。

onUpdateClick(updateHash, updateHeight, updateSize, updateTime) {
//this is the url where the post will be made
this.url = "http://localhost:3000/api/blockinfo/" + updateHash.toString();

//those are the variables in the object stored in the database (url)
var height;
var size;
var time;

//this is the original object before any modification
var nullCase;

nullCase = this.http.get(this.url)

//those if's mean that if one of the fields in the form is null (non filled) , I will check for the object before the modification (nullCase),and use its previous values in the update
if (updateHeight == null) {
height = Number(nullCase.height)
} else {
height = Number(updateHeight)
}

if (updateSize == null) {
size = Number(nullCase.size)
} else {
size = Number(updateSize)
}

if (updateTime == null) {
time = Number(nullCase.time)
} else {
time = Number(updateTime)
}



//after all the above checks, I want my current object to get its values assigned and ready to be posted
this.body = {
"hash": updateHash.toString(),
"height": height,
"size": size,
"time": time
}

//after the object to post is ready, I want to make the post into the database
this.http.post(this.url, this.body).subscribe((result) => {
console.log(result)
});


}

但是似乎一切都不同步,因为除了检查之外我还得到了空对象

最佳答案

1) 您将订阅分配给 nullCase,这是没有意义的。

nullCase = this.http.get(this.url).subscribe(result => {}); // Wrong
this.http.get(this.url).subscribe(result => { nullCase = result });

2) Get 是异步的,您需要在回调函数中编写依赖于结果的代码

// Wrong
this.http.get('url').subscribe(result => { nullCase = result });
this.http.post('url', {}).subscribe(result => { // Something using nullCase });

// Should be
this.http.get('url').subscribe(result => {
this.http.post('url', {});
});

3)更好的是,您不应该嵌套订阅,您应该使用 rxjs 运算符:

this.http.get("").pipe(
switchMap(result => {
return this.http.post("", {});
})
).subscribe();

关于javascript - 异步 POST 到数据库时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56036356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com