javascript - Asyncronus React-Native
问题描述
问题:异步代码导致整个源代码遵循异步
例子:
// global scope
let _variableDefinedInParentScope
WriteConfiguration(__params) {
// overSpreading.
let { data, config } = __params
// local variable.
let _fileName, _configuration, _write, _read
// variable assignment.
_fileName = config
_configuration = data
// if dataset and fileName is not empty.
if(!_.isEmpty(_configuration) && !_.isEmpty(_fileName)) {
// create a path you want to write to
// :warning: on iOS, you cannot write into `RNFS.MainBundlePath`,
// but `RNFS.DocumentDirectoryPath` exists on both platforms and is writable
_fileName = Fs.DocumentDirectoryPath + ' /' + _fileName;
// get file data and return.
return Fs.readDir(_fileName).then((__data) => {
console.error(__data)
// if data is not empty.
if(!_.isEmpty(__data)) {
// return data if found.
return __data
} else {
// write the file
return Fs.writeFile(_fileName, data, 'utf8')
.then((success) => {
// on successful file write.
return success
})
.catch((err) => {
// report failure.
console.error(err.message);
})
}
})
.catch((err) => {
// report failure.
console.error(err.message)
})
}
} // write configuration to json file.
以下是承诺处理的方法
- .then((__onAccept)=>{}, (__onReject) => {})
- aync 函数 (__promise) { 等待 WriteConfiguration() }
- .then((_onAccept) => { _variableDefinedInParentScope = __onAccept }
据我所知,第三个是无用的,因为我从未遇到过任何回报,因为承诺正在解决需要时间,并且在任何解决之前调用该变量将返回未定义
React-native 在 react-native 中,几乎每个代码部分都是同步的,其中文件写入模块是异步的,这给我带来了麻烦。
我想要什么我想 从异步返回值到同步代码。没有任何异步链。
解决方案
您的答案很简单,使用
await
和
async
例子:
mainFunction(){
//will wait for asyncroFunction to finish!!
await asyncroFunction()
}
async asyncroFunction(){
}
推荐阅读
- iot - 使用 Cumulocity 将用户添加到组
- react-native - 应用重新加载后不显示来自本地 uri (file:///[...]/cache/[...].jpg) 的图像
- python-3.x - 从 excel 表格到 OrderedDict
- pandas - 如果满足条件,两列的差异
- c# - ServiceStack 试图绑定通过服务引用而不是公共属性生成的私有字段类
- ruby - 如何在红宝石中初始化winium?
- excel - 选择最小范围?
- javascript - 将文本类型输入更改为格式化密码
- java - 在 Jboss 上为 JAX-RS 2.0 / Resteasy 客户端设置超时
- c# - 如何在 WPF 中存储 DatePicker 中的值?