亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Fetch() 亂序運行

Fetch() 亂序運行

夢里花落0921 2023-05-25 16:56:18
我正在嘗試讓 API 提取一個詞并將其設置為狀態。然后一個函數將讀取該狀態并完成其設計目的。然而,我最初編碼它的方式稱它為亂序。第三個代碼片段允許代碼成功運行,但我不確定為什么。有人能解釋一下有什么區別或者為什么原來的方法不起作用嗎?下面是第二個函數后面的 API 函數。wordNikApi = () => {        fetch("http://api.wordnik.com:80/v4/words.json/randomWords?hasDictionaryDef=true&minCorpusCount=0&minLength=5&maxLength=15&limit=1&api_key=/* Removed */")            .then( res => res.json() )            .then( ( result ) => {                this.setState({                    apiWord: result[0].word,                });                console.log("wordNikApi: ", this.state.apiWord);            })            .catch( ( error ) => {                console.log("API ERROR: ", error);            })    };resetGame = () => {        console.log("resetGame");        this.wordNikApi();        this.setState({             word: [],            count: 0,            allAttempts: [],            letterIndex: [],            numberOfBadAttempts: 0,            remainingAttempts: 6,            repeat: false,            pageLock: false,            invalidKey: false,        }, () => {            console.log("resetGame: function 1");            console.log(this.state.apiWord);            let fullWord = "word";            let wordArray = fullWord.split("");            let wordLength = wordArray.length;            // Send wordObj to state with value and index            let wordObj = wordArray.map((value, index) => {                return {                    found: false,                    val: value,                    id: index,                }            })            this.setState({                 word: wordObj,                wordLength: wordLength,                remainingAttempts: 6,            });        });    };
查看完整描述

3 回答

?
DIEA

TA貢獻1820條經驗 獲得超2個贊

導致你出現問題的是JS異步,當你在resetGame函數中調用wordNikApi函數時,你必須使用await關鍵字,這樣才能先生成對wordNijApi函數的更改,然后繼續流程工作。嘗試像這樣修改 resetGame 函數:


const resetGame = async()=>{

...


await this.wordNikApi()

...

}


查看完整回答
反對 回復 2023-05-25
?
蠱毒傳說

TA貢獻1895條經驗 獲得超3個贊

Fetch 是一個異步函數,這意味著它將與您的其他代碼一起運行,調用設置this.wordNikApi()獲取請求,但不會阻止您繼續編寫腳本。

在您的新版本中,函數內部有代碼.then(),當提取請求調用數據并返回時調用該函數,因此您的代碼在此處等待完成,this.wordNikApi()然后在第三個代碼段中運行。

希望這有助于更清楚地了解 Async 和 Sync,但是有更好的文檔可以解釋這一點。


查看完整回答
反對 回復 2023-05-25
?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

我實現了一個隊列,它在隊列中的第一個項目上調用 fetch,然后使用 fetch().then 來拉下一個項目,發布它,然后如果隊列不為空則重復執行。這是我使用的代碼:


var clientDataQueue = [];

function queueClientData(theData) {

? ? clientDataQueue.push(theData);

? ? console.log("++clientDataQueue.length:", clientDataQueue.length)

? ? if (clientDataQueue.length == 1){

? ? ? ? postFromQueue();

? ? }

}


function postFromQueue() {

? ? console.log("--clientDataQueue.length:", clientDataQueue.length)

? ? if (clientDataQueue.length > 0) {

? ? ? ? postClientdata(clientDataQueue[0]).then( () => {

? ? ? ? ? ? clientDataQueue.shift();

? ? ? ? ? ? postFromQueue();

? ? ? ? });

? ? }

}


function postClientdata(theData) {

? ? var htmlData = {

? ? ? ? method: 'POST',

? ? ? ? headers: {

? ? ? ? ? ? 'Content-Type': 'application/json'

? ? ? ? },

? ? ? ? body: JSON.stringify(theData)

? ? };

? ? return fetch('/api/clientData', htmlData)

}


查看完整回答
反對 回復 2023-05-25
  • 3 回答
  • 0 關注
  • 197 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號