为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 111 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信