I could not get readFile() to work with async/await correctly. I wanted a function to return results from readFile converted to json, using await to wait for the read to complete. Something like this:
async function func() {
const path = "abc";
let contents;
contents = await RNFS.readFile(path);
let j = json.parse(contents);
return j;
}
Then I would simply call this function (in another function):
val = func()
But it appeared that func() returned immediately before the file was actually read. That is not what I was expecting. When using the promise directly and .then syntax, everything was fine.
Not sure if I am totally wrong about how to do this, or if there is an issue. Thanks!
When you do val = func(), val contains the Promise, not the result of promise. You have to await your func, which returns a promise returning parsed file, i.e. val = await func(). When you use such syntax, the containing function also has to be async.
Thanks, my mistake.
I'm having a similar issue and it's really confusing.
export const getPaths = async (pathsUpdated) => {
let filesList = []
internal = '/sdcard/Download/place'
external = '/storage/1111-2222/Download/place'
intPaths = await getFilePaths(internal)
extPaths = await getFilePaths(external)
filesList.push(intPaths)
filesList.push(extPaths)
console.log("filesList\t" + filesList) // filesList [object Object],[object Object]
return filesList
}
// attempt 1
getFilePaths = async (path) => {
console.log('reading from:\t' + path)
let files = await RNFS.readDir(path)
console.log("found:\t" + files) // found: [object Object]
return files
}
If you want to console.log an object, you can do it like this:
console.log("found:\t" + JSON.stringify(files)) // found: {"something":{"blah":"x"}}
This is my second version. What could possibly be wrong?
export const getPaths = async (pathsUpdated) => {
let filesList = []
internal = '/sdcard/Download/place'
external = '/storage/1111-2222/Download/place'
intPaths = await getFilePaths(internal)
extPaths = await getFilePaths(external)
filesList.push(intPaths)
filesList.push(extPaths)
console.log(filesList)
return filesList
}
getFilePaths = async (path) => {
console.log('reading from:\t' + path)
let files = await RNFS.readDir(path)
console.log("found:\t" + JSON.stringify(files))
return files
}
Error: Attempt to get length of null array but I'm sure there are files in there. It was working just yesterday.
Ah, according to this thread on StackOverflow Android will return null when path does not exist. Can you first try to check if the directory exists?
Yeah it does
There is one more option, you may miss the following permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I updated that and did a ./gradlew clean && ./gradlew installDebug. I don't know what's wrong here.
Me neither 馃槥
any updates?