Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将顺序设置为React Native中的函数_Javascript_React Native - Fatal编程技术网

Javascript 将顺序设置为React Native中的函数

Javascript 将顺序设置为React Native中的函数,javascript,react-native,Javascript,React Native,我在componentDidMount中有2个函数 componentDidMount() { this.m1(); this.m2(); } m1下载了一个我在m2中使用的文件,但是当我运行应用程序时,我得到了一个错误,因为m2在m1之前运行 有没有办法设置我想要的顺序,让m1先下载文件,然后运行m2?您可以像这样使用回调 componentDidMount() { this.m1(params, function(){ this.m2();

我在componentDidMount中有2个函数

componentDidMount() {
    this.m1();
    this.m2();
}
m1下载了一个我在m2中使用的文件,但是当我运行应用程序时,我得到了一个错误,因为m2在m1之前运行


有没有办法设置我想要的顺序,让m1先下载文件,然后运行m2?

您可以像这样使用回调

componentDidMount() {
    this.m1(params, function(){
        this.m2();
    });
}

function: m1(params, callback) {
    ...
    ...
    callback();
}

在某些情况下,如果使用承诺,这些函数可能会更高效、更可读。承诺可以帮助您避免所有的“回调地狱”,将来您将能够以最简单的方式理解任何异步和嵌套函数的所有功能

例如(您应该将代码调用一个copule of times来查看错误或成功)

constMyAsyncFunction=()=>{
返回新承诺((解决、拒绝)=>{
//一些逻辑,例如1和10之间的随机数。
//randomNumber应小于5。否则,将不会调用MySyncFunton
var myRandomNumber=Math.floor((Math.random()*10)+1);
setTimeout(()=>{
如果(myRandomNumber){
//一些逻辑
console.log('SyncFunction,randomNumber为param=>'+number)
};
//主同步功能
var consoleLOGS=myAsyncFunction()
.then((response)=>{//来自resolve()方法的第一个响应
mySyncFunction(响应)
return(response)//您可以将响应传递给second then()方法
})
.then((newResponse)=>console.log('success,mySyncFunction已执行,第二个then中收到参数='+newResponse))

.catch((error)=>console.log('error,mySyncFunction未执行,'+error.message))
有很多方法,这取决于你希望你的代码有多干净。你还有比m1和m2更多的函数吗?是的,现在总共有1个,3个。对不起,我很抱歉。你可以看到这些示例选择哪一个对你最干净和有益。我在这一行中不断遇到错误->函数:m1(参数,回调)。错误:绑定:SyntaxError:…/home.js:意外标记,应为;