5 回答

TA貢獻1864條經驗 獲得超2個贊
您需要將函數本身而不是其結果傳遞給then
:
.then(this.the2ndFunction)
否則,您可能會在 fetch 事件返回之前執行第二個函數。
此外,對看似兩個嚴格順序的函數使用 Promise 是沒有必要的。

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)

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()
}

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
}
}

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);
});
}
添加回答
舉報