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);
});
}
添加回答
举报