我創建了一個 IG 喜歡按鈕,點擊后喜歡的數量會發生變化。我添加了 2 個獲取函式 - 一個帶有 PUT。我嘗試了多種方法,但結果都是一樣的 - 首先執行 GET fetch。我怎樣才能防止這種情況?
function liking(tweetid) {
let l = document.querySelector('#numlikes-' tweetid);
fetch(`tweets/${tweetid}`, {
method: 'PUT',
body: JSON.stringify({
tweet_like: 1
})
});
fetch(`tweets/${tweetid}`)
.then(response => response.json())
.then(post => {
l.innerHTML = post.likes;
});
}
uj5u.com熱心網友回復:
Javascript 是一種同步語言,一行代碼默認是不等待 line 之前完成的。通過不重要且無關緊要的近乎即時的操作。在這里,由于 fetch 需要與服務器通信,因此您的第二次 fetch 在第一個完成之前就開始了。有兩個簡單的解決方案可以解決這個問題
使用異步等待
從 ES6 開始,我們可以使用 async await:
async function liking(tweetid) {
let l = document.querySelector('#numlikes-' tweetid);
await fetch(`tweets/${tweetid}`, {
method: 'PUT',
body: JSON.stringify({
tweet_like: 1
})
});
await fetch(`tweets/${tweetid}`)
.then(response => response.json())
.then(post => {
l.innerHTML = post.likes;
});
}
鏈接.then:
function liking(tweetid) {
let l = document.querySelector('#numlikes-' tweetid);
fetch(`tweets/${tweetid}`, {
method: 'PUT',
body: JSON.stringify({
tweet_like: 1
})
}).then(() => {
fetch(`tweets/${tweetid}`)
.then(response => response.json())
.then(post => {
l.innerHTML = post.likes;
});
});
}
uj5u.com熱心網友回復:
fetch是一個異步函式。這意味著您無法預測fetch首先收到哪個回應。要使其按順序呼叫,您應該fetch在 PUT 的回應回呼中呼叫 GET fetch。
function liking(tweetid) {
let l = document.querySelector('#numlikes-' tweetid);
fetch(`tweets/${tweetid}`, {
method: 'PUT',
body: JSON.stringify({
tweet_like: 1
})
}).then(() => {
fetch(`tweets/${tweetid}`)
.then(response => response.json())
.then(post => {
l.innerHTML = post.likes;
});
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352808.html
標籤:javascript 姜戈 拿来
上一篇:帶有變數的打字稿型別注釋
