then() 内部的 fetch 第一次 onClick() 不起作用

问题描述 投票:0回答:1

所以我试图制作一个表单,在提交时调用此代码。

async function addListing() {
        let listing: any = {
            make: make,
            model: model,
            year: year,
            mileage: mileage,
            price: price
        };

        await fetch("http://localhost:8080/api/listing", {
            method: "POST", 
            headers: {"Content-type": "application/json"},
            body: JSON.stringify(listing)
        })
        .then(() => {
            fetch("http://localhost:8080/api/listing")
            .then(res => res.json())
            .then(data => {
                setListingID(data[data.length - 1].id);
            })
            .catch(error => {
                console.log(error);
            });
        })
        .then(() => {
            console.log("Listing: ", listingId, " Seller: ", sellerId)
        })
        .catch(error => {
            console.log(error)
        })
    }

post 函数工作正常,但是第一个 then() 内的 get 函数在第一次单击按钮时不起作用。 因此,当我第一次单击提交按钮时,我得到:“列表:卖家:3” 第二次(以及此后的每次)都是正确的,例如:“列表:123 卖家:3”

我昨天尝试了所有方法来找到一个解决方案,我做了一个单独的功能,但它不起作用今天我搜索了整个互联网,尝试了很多东西,但我似乎找不到我做错了什么。

当我让它工作时,我想使用该listingId函数来调用另一个函数,该函数将在单独的表中连接listingId和sellerId。

javascript fetch
1个回答
2
投票

您在调试中做出了错误的假设。所讨论的

.then()
回调正在调用异步操作,但没有任何东西 等待 该操作。所以它立即移动到链中的下一个
.then()

返回

Promise

.then(() => {
  return fetch("http://localhost:8080/api/listing")
     .then(/* etc... */);
})

退一步...混合

await
.then()
回调会导致混乱。既然你正在使用 async/await,为什么不使用 async/await呢?例如:

try {
  await fetch("http://localhost:8080/api/listing", {
    method: "POST", 
    headers: {"Content-type": "application/json"},
    body: JSON.stringify(listing)
  });
  const res = await fetch("http://localhost:8080/api/listing");
  const data = await res.json();
  setListingID(data[data.length - 1].id);
  console.log("Listing: ", listingId, " Seller: ", sellerId);
} catch (error) {
  console.log(error)
}

另外...

这是React吗?:

setListingID(data[data.length - 1].id);

如果是这样,请参阅useState set 方法没有立即反映更改

状态更新是异步的(并且不可等待)。如果您在调用状态更新后立即需要该值,请将其存储在变量中。例如:

const data = await res.json(); const newListingID = data[data.length - 1].id; setListingID(newListingID); console.log("Listing: ", newListingID, " Seller: ", sellerId);
    
© www.soinside.com 2019 - 2024. All rights reserved.