Skip to content
This repository was archived by the owner on Mar 16, 2019. It is now read-only.

Example code for writeStream ignores that stream.write() returns a promise? #467

Closed
lll000111 opened this issue Aug 8, 2017 · 6 comments

Comments

@lll000111
Copy link
Contributor

The example code at https://github.com/wkh237/react-native-fetch-blob#file-stream completely ignores the promise returned by the write function.

Now I wonder, if it does not matter, why return a promise? But if it matters, don't I have to wait for the promise? One, to be sure of success, two, for sequencing the writes correctly?

@wkh237
Copy link
Owner

wkh237 commented Aug 8, 2017

Well, basically it does not matter because the fs I/O operations are queued and executed in the same thread.

@lll000111
Copy link
Contributor Author

lll000111 commented Aug 8, 2017

That leaves open the problem of a rejected writer promise though....

The example code is

RNFetchBlob.fs.writeStream(
    PATH_TO_FILE,
    // encoding, should be one of `base64`, `utf8`, `ascii`
    'utf8',
    // should data append to existing content ?
    true)
.then((ofstream) => {
    ofstream.write('foo')
    ofstream.write('bar')
    ofstream.close()
})

In the above code any rejected write() promise will be ignored.

It should be something like

async function write () {
    const ofstream = await RNFetchBlob.fs.writeStream(
        PATH_TO_FILE,
        // encoding, should be one of `base64`, `utf8`, `ascii`
        'utf8',
        // should data append to existing content ?
        true
    ;)

    // IF ANY OF THESE PROMISES REJECT THIS WHOLE FUNCTION WILL TOO
    await ofstream.write('foo');
    await ofstream.write('bar');
    await ofstream.close();
}

With pure promise notation it's more difficult because only the first one in the .then() chain gets the stream object - the write() command unfortunately resolves with undefined in case of success, if it would resolve with the stream object promise chaining would be simple.

@lll000111
Copy link
Contributor Author

lll000111 commented Aug 9, 2017

Suggestion (very short PR on the way): If write() resolves with the RNFetchBlobWriteStream instance instead of with undefined the write calls can be chained:

[return to calling function] RNFetchBlob.fs.writeStream(PATH_TO_FILE, 'utf8', true)
.then((ofstream) => ofstream.write('foo'))
.then((ofstream) => ofstream.write('bar'))
.then((ofstream) => ofstream.write('foobar'))
.then((ofstream) => ofstream.close())

No more issues with unhandled rejections, AND the returned promise now resolves when the last write actually happened, the original example code resolves when the stream object is created.

This is optional, since writes are in the order they are issued (Are they? Does the low-level iOS and Android code guarantee that?) an alternative is to issue all writes at once:

[return to calling function] RNFetchBlob.fs.writeStream(PATH_TO_FILE, 'utf8', true)
.then((ofstream) => Promise.all([
    ofstream.write('foo'),
    ofstream.write('bar'),
    ofstream.write('foobar')
]))
// Use array destructuring to get the stream object from the first item
.then(([ofstream]) => ofstream.close())

@lll000111
Copy link
Contributor Author

lll000111 commented Aug 9, 2017

@wkh237 I don't understand how Github and git work. When I try to create a pull request all the previous changes from the already merged pull request from yesterday are in it again! Even though I update my local repo!

Could you please insert this tiny(!) patch (change resolve()to resolve(this)) manually? I HATE git, it is WAY too complex (the correct word: not complicated but complex - complexity arises from interactions of by themselves very simple things)

How do I get new pull requests to only show NEW commits, and not stuff that has already been merged? Why won't let Github let me select the commits I want to put into a pull request?

I still don't know how it works, but I managed to create a pull request that shows only the relevant two lines in the diff (1 code line, 1 Flow type annotation for the function's return type).

@lll000111 lll000111 mentioned this issue Aug 9, 2017
wkh237 pushed a commit that referenced this issue Aug 9, 2017
* bump to 0.10.8

* Update PULL_REQUEST_TEMPLATE

* Fix #468 "Messy error returns: Sometimes a string, sometimes an Error object"

* Cleanup: remove an unused constant and duplicate method definitions

* Cleanup:
- fix minor errors in JSDoc comments, for example {string]} => {string}
- fix parameter name "encode" => "encoding" (more logical, and it says so in the function's JSDoc too)
- json-stream.js: split a looooong log message string constant into two parts and fix a typo ("maually"), and the type for objects is "Object" (capitalized) in Flow type annotations

* Fix a (Flow) type conflict - fixes issue #461

* NEEDS REVIEW - Attempt to fix some of issue #460 (Error message normalization)

Error messages reported by iOS and Android versions should be as similar as possible. Also, within the same system there should be consistency. This patch is an attempt to bring a LITTLE more of this consistency to the error messages. I also fixed some very few minor language issues, like "does not exist" (is the correct English). I tried keeping the changes to a minimum.

Background: In my project code I want to know when a file already exists (e.g. after calling fs.createFile), and the only way is to check the error message string that I get. It's bad if they differ between versions (createFileASCII and createFile) and then also between Android and iOS version. At least some core part of the string should be the same, so that I have something to match.

Ideally messages should come from a centralized easy (easier) to maintain file (for both iOS and Android), and ideally both systems should have the same errors and messages as far as possible.

* Fixes #467 by improving the write() function of write streams: By resolving with the RNFetchBlobWriteStream instance instead of with "undefined" writes can now be chained:

RNFetchBlob.fs.writeStream(PATH_TO_FILE, 'utf8', true)
.then((ofstream) => ofstream.write('foo'))
.then((ofstream) => ofstream.write('bar'))
.then((ofstream) => ofstream.write('foobar'))
.then((ofstream) => ofstream.close())

Reference: #467 (comment)
@lll000111
Copy link
Contributor Author

lll000111 commented Aug 9, 2017

@lll000111 TODO for myself: PR to update the documentation for 0.10.9 too

Note to myself: Also fix the link to the hash() function Wiki page while editing the README.md file.

@lll000111
Copy link
Contributor Author

lll000111 commented Aug 16, 2017

I'm closing it here and create a link to this issue in my own folk of this repo.

wkh237 pushed a commit that referenced this issue Aug 31, 2017
* fs.js: forgot one more error refactoring

* Fix path argument in iOS excludeFromBackupKey (#473)

* Fix link to fs.readStream() and to fs.writeStream() and insert link to new function fs.hash()

* Fix the documentation part of #467 "Example code for writeStream ignores that stream.write() returns a promise?"

* More fixes for issue #460 "Error normalization"

IMPORTANT: I wrote the iOS code BLIND (not even syntax highlighting) - this needs to be tested.

- Two or three methods that used callbacks to return results were changed to RN promises
- All methods using promises now use a Unix like code string for the first parameter, e.g. "ENOENT" for "File does not exist" (http://www.alorelang.org/doc/errno.html). The React Native bridge code itself uses this schema: it inserts "EUNSPECIFIED" when the "code" it gets back from Android/iOS code is undefined (null, nil). The RN bridge assigns the code (or "EUNSPECIFIED") to the "code" property of the error object it returns to Javascript, following the node.js example (the "code" property is not part of "standard" Javascript Error objects)
- Important errors like "No such file" are reported (instead of a general error), using the code property.
- I added a few extra error checks that the IDE suggested, mostly for Android (for which I have an IDE), if it seemed important I tried to do the same for teh iOS equivalent function
- I followed IDE suggestions on some of the Java code, like making fields private
- RNFetchBlobFS.java removeSession(): Added reporting of all failures to delete - IS THIS DESIRABLE (or do we not care)?
- readStream: The same schema is used for the emitted events when they are error events
- iOS: added an import for the crypto-digest headers - they are needed for the hash() function submitted in an earlier commit
- Fixed a link in the README.md - unfortunately the anchor-links change whenever even one character of the linked headline in the Wiki page changes

* Fix one issue raised in #477 by using code from https://stackoverflow.com/a/40874952/544779

* fix some access rights, remove unused items

* update gradle version setting in build.gradle

* Revert gradle settings to previous values :-(

* add a missing closing ")"

* Removed the part of an obsolete callback function parameter that I had left in when I converted mkdir to promises (low-level code)

* let mkdir resolve with "undefined" instead of "null" (my mistake)

* mkdir: normalize iOS and Android error if something already exists (file OR folder); return "true" (boolean) on success (failure is rejected promise) - it is not possibel to return "undefined" from a React Native promise from Java

* fix a long/int issue

* my mistake - according to https://facebook.github.io/react-native/docs/native-modules-android.html#argument-types "long" is not possible as argument type of an exported RN native module function

* Adde "utf8" as default encoding for fs.readFile - fixes #450 and #484

* follow my IDEA IDE's recommendations - SparseArray instead of HashMap, and make some fields private

* polyfill/File.js: add a parameter===undefined? check (this happened silently in the test suite)

* make var static again

* Normalized errors for fs.ls()

* forgot one parameter

* more parameter checks

* forgot to resolve the promise

* Forgot ;

* add more error parameter checks

* change readStream()/writeStream() default encoding to utf8 to match the tests in react-native-fetch-blob-dev

* default encoding is set in fs.js (now), no need to do it twice

* ReadStream error events: Set a default error code "EUNSPECIFIED" if no code is returned (should not happen, actually)

* writeFile() Android and iOS: improve errors; ReadStream: Add "ENOENT" (no such file) error event to Android version and add the thus far missing "code" parameter to iOS version

* oops - one "}" too many - removed

* add EISDIR error to readFile()s error vocabulary (iOS and Android)

* "or directory" is misplaced in a "no such file" error message for readFile()

* Android: two reject() calls did not have a code, iOS: slice() did not have code EISDIR, and "could not resolve URI" now is EINVAL everywhere

* writeStream: return ENOENT, EISDIR and EUNSPECIFIED according to the normalized schema (#460); Open a new question about behavior on ENOENT (#491)

* "+ +" was one plus sign too many

* this if has a whole block (that ois why I prefer a style where {} are mandatory even for single-statement blocks)

* I renamed this variable

* 1) #491 "writeStream() does not create file if it doesn't exist?"
2) I had gone overboard with the "@[..]" in the ios code, making some error strings arrays
3) fix typos: rename all ENODIR => ENOTDIR

* Java: getParentFolder() may return null - prevent a NullPointerException by adding one more check

* Relating to #298 -- looping through an array is not supposed to be done with for...in

*  Fix IOS syntax errors in #489

* #489 Fix typo and missing return statement

* fix error code
danielsuo added a commit to danielsuo/react-native-fetch-blob that referenced this issue Feb 13, 2018
* upstream/0.10.9:
  Fixed problem with type casting (wkh237#513)
  My proposed 0.10.9 changes (wkh237#489)
  wkh237#268 Cancelled task should not trigger `then` promise function
  Add ability to cancel android DownloadManager fetches (wkh237#502)
  Fix iOS initialization race condition (wkh237#499)
  prevent UIApplication methods from being called on background thread (wkh237#486)
  Implemenet fs.hash() -- wkh237#439 "Feature: Calculate file hash" (wkh237#476)
  I forgot one error string for the Android readFile() method (wkh237#475)
  Fix for wkh237#467 (wkh237#472)
  Fix for issue wkh237#468, wkh237#461, wkh237#460 and minor cleanup (wkh237#469)
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants