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

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

等待函數完成后再繼續

等待函數完成后再繼續

至尊寶的傳說 2023-07-14 15:48:14
我有這 3 個需要按順序運行的函數。然而,由于first function其中有一個循環,因此它們2nd and 3rd functions在第一個函數的數據可用之前完成。我如何重構它以保證每個任務在下一個任務開始之前按順序完成?過去的使用.then已經給了我我所需要的。但這一次它沒有按正確的順序完成。mainFunction() {        fetch(API_URL + `/dataToGet`)            .then((res) => {                if (!res.ok) {                    throw new Error();                }                return res.json();            })            .then((result) => {                this.setState({data: result}, () => this.1stFunction());                console.log(result);            })            .catch((error) => {                console.log(error);            })            .then(this.2ndFunction())            .catch((error) => {                console.log(error);            })            .then(this.3rdFunction());  }firstFunction(){for (let i = 0; i < data.length; i++){            for (let j = 0; j < 8; j++){               //...grabbing data and saving to variables to be used in next steps...             }        }}secondFunction(){... wait until firstFunction is completed and then do something with data...}thridFunction(){... wait until secondFunction is complete and then do something else with that data...}
查看完整描述

5 回答

?
慕斯王

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

您需要將函數本身而不是其結果傳遞給then

.then(this.the2ndFunction)

否則,您可能會在 fetch 事件返回之前執行第二個函數。

此外,對看似兩個嚴格順序的函數使用 Promise 是沒有必要的。


查看完整回答
反對 回復 2023-07-14
?
溫溫醬

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

這樣做.then(this.2ndFunction())是錯誤的,因為函數會立即執行


這3個功能是同步的嗎?setState如果是,你可以在回調中調用這些函數


mainFunction() {

  fetch(API_URL + `/dataToGet`)

    .then((res) => {

      if (!res.ok) {

        throw new Error();

      }

      return res.json();

    })

    .then((result) => {

      this.setState({data: result}, () => {

        this.1stFunction();

        this.2ndFunction();

        this.3rdFunction();

      });

    })

    .catch((error) => console.log(error));

}

如果這些函數是異步的,您只需從這些函數返回一個 Promise 并更新您的代碼,如下所示:


.then((result) => {

  return new Promise((resolve, reject) => {

    this.setState({data: result}, () => {

      this.1stFunction().then(resolve, reject);

    });

  }

})

.catch(console.log)

.then(this.2ndFunction)

.catch(console.log)

.then(this.3ndFunction)

.catch(console.log)


查看完整回答
反對 回復 2023-07-14
?
吃雞游戲

TA貢獻1829條經驗 獲得超7個贊

如果你的所有功能都是同步的,你可以這樣做


const res = this.1stFunction();

this.setState({data: result}, () => res);

this.2ndFunction()

this.3rdFunction()

如果它們是異步的


async function function_name(){

    const res = await this.1stFunction();

    this.setState({data: result}, () => res);

    await this.2ndFunction()

    await this.3rdFunction()

}


查看完整回答
反對 回復 2023-07-14
?
瀟瀟雨雨

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

async 和await 將等待一個調用完成,然后只有它才會移動到函數中的下一行。


async mainFunction() {

  try{

    const api = await fetch(API_URL + `/dataToGet`);

    const fistUpdate = await this.1stFunction(api);

    const secondUpdate = await this.2stFunction(fistUpdate);

    const thirdUpdate = await this.3stFunction(secondUpdate);

  } catch(){

  //error handling

  }

}


查看完整回答
反對 回復 2023-07-14
?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

讓第一個、第二個和第三個函數返回 Promise.resolve(),然后:


mainFunction() {

        fetch(API_URL + `/dataToGet`)

            .then((res) => {

                if (!res.ok) {

                    throw new Error();

                }

                return res.json();

            })

            .then((result) => {

                this.setState({data: result}, () => {

                    this.1stFunction().then(() => {

                        this.2ndFunction().then(() => {

                            this.3rdFunction();

                        });

                    });

                });

                console.log(result);

            })

            .catch((error) => {

                console.log(error);

            });

  }


查看完整回答
反對 回復 2023-07-14
  • 5 回答
  • 0 關注
  • 210 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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