首页 > 解决方案 > 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.

以下是承诺处理的方法

据我所知,第三个是无用的,因为我从未遇到过任何回报,因为承诺正在解决需要时间,并且在任何解决之前调用该变量将返回未定义

React-native 在 react-native 中,几乎每个代码部分都是同步的,其中文件写入模块是异步的,这给我带来了麻烦。

我想要什么我想 从异步返回值到同步代码。没有任何异步链。

标签: javascriptreact-nativeasynchronousasync-await

解决方案


您的答案很简单,使用

 await

 async

例子:

mainFunction(){
  //will wait for asyncroFunction to finish!!
  await asyncroFunction()
}

async asyncroFunction(){
}

推荐阅读