我在 componentDidMount 中有 2 个函数
componentDidMount() {
this.m1();
this.m2();
}
m1 下载我在 m2 中使用的文件,但是当我运行该应用程序时,我收到一个错误,因为 m2 在 m1 之前运行。
有没有办法设置我想要的顺序,以便 m1 先下载文件,然后运行 m2?
在某些情况下,如果您使用承诺,这些函数可能会更高效和可读。Promise 可以帮助您防止所有“回调地狱”,将来您将能够以最简单的方式理解任何异步和嵌套函数的所有功能。
例如(您应该多次调用代码以查看错误或成功)
const myAsyncFuntion = () => {
return new Promise ((resolve, reject) => {
//Some Logic for example a random number betweeen 1 and 10.
//randomNumber should be smaller than 5. if not, the mySyncFuntion wont be called
var myRandomNumber = Math.floor((Math.random() * 10) + 1);
setTimeout(() =>{
if(myRandomNumber <= 5){
console.log('AsyncFunction with randomNumber = ' + myRandomNumber)
resolve(myRandomNumber);
}else{
console.log('AsyncFunction, with randomNumber = ' + myRandomNumber)
reject(new Error('randomNumber ' + myRandomNumber + ' is bigger than 5'))
}
}, 1000)
})
};
const mySyncFunction = (number) => {
//Some Logic
console.log('SyncFunction, randomNumber as param =>' + number)
};
//MAIN SYNCHRONOUS FUNCTION
var consoleLOGS = myAsyncFuntion()
.then((response) => { //first response from the resolve() method
mySyncFunction(response)
return (response) // you can pass the response to second then() method
})
.then((newResponse) => console.log('success, mySyncFunction executed, param recived in 2nd then = ' + newResponse))
.catch((error) => console.log('error, mySyncFunction wasnt executed, ' + error.message))
请注意,虽然异步函数需要 1000 毫秒才能执行,但它比同步函数的主要功能先运行console.log()
,花费的时间更少。不要忘记在componentDidMount()
你应该调用的方法中......
myAsyncFuntion()
.then((response) => {
mySyncFunction(response)
return (response) // you can pass the response to second then() method
})
.then((newResponse) => console.log('success... second then = ' + newResponse))
.catch((error) => console.log('error catched, ...' + error.message))
最后,如果函数的定义const
是在主组件上定义的,则应该在没有类型的情况下编写函数的定义。回调非常好,但 Promise 更好,更具可读性。我相信你可以用 Promise 做更多的逻辑和实现。
如果您正在处理 API 请求,则可以使用 axios 或 fetch。也许您正在使用 firebase 作为数据库并且许多函数都是 THENABLE,这意味着您可以访问 then 和 catch 方法,因为有从服务器返回的承诺。
看看这里https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句