react-native 中promise使用
2020-07-20 本文已影响0人
喜剧收尾_XWX
1.返回一个promise
getTheme(){
return new Promise((resolve,reject)=>{
AsyncStorage.getItem(Theme_key,(error,result)=>{
if (error) {
reject(error);
return;
}
if (!result) {
this.save(ThemeFlags.Default);
result = ThemeFlags.Default;
}
resolve(ThemeFactory.createTheme(result));
})
})
}
- 使用
new ThemeDao().getTheme().then((data)=>{
dispatch(onThemeChange(data))
}).catch(e=>{
console.log(e)
})
loadData2(){
let url = `https://api.github.com/search/repositories?q=${this.searchKey}`;
fetch(url)
.then(response => {
console.log("response: " + response);
if(response.ok){
return response.text();
}
throw new Error ("服务没有响应");
})
.then(responseText => {
this.setState({
showText:responseText
})
})
.catch(e => {
alert(e.toString());
this.setState({
showText:e.toString
})
})
}
3.使用async和await接收promise
export function onLoadLanguage(flagkey){
return async dispatch =>{
try{
//这里返回的是一个promise
let languages = await new LanguageDao(flagkey).fetch();
dispatch({type:types.LANGUAGE_LOAD_SUCCESS,languages:languages,flag:flagkey})
}catch(e){
}
}
}