Skip to content

Commit

Permalink
Move internal functions to async/await (#578)
Browse files Browse the repository at this point in the history
* Update functions to use modern javascript (use async/await instead of promises)

* Remove unnecessary try/catch

* Fix formating

* Revert use of Fetch

---------

Co-authored-by: Arun Bohra <[email protected]>
  • Loading branch information
Acconut and ArunBohra12 authored Apr 6, 2023
1 parent 17878d7 commit 01d3948
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 24 deletions.
17 changes: 9 additions & 8 deletions lib/browser/fileReader.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,20 @@ import FileSource from './sources/FileSource.js'
import StreamSource from './sources/StreamSource.js'

export default class FileReader {
openFile(input, chunkSize) {
async openFile(input, chunkSize) {
// In React Native, when user selects a file, instead of a File or Blob,
// you usually get a file object {} with a uri property that contains
// a local path to the file. We use XMLHttpRequest to fetch
// the file blob, before uploading with tus.
if (isReactNative() && input && typeof input.uri !== 'undefined') {
return uriToBlob(input.uri)
.then((blob) => new FileSource(blob))
.catch((err) => {
throw new Error(
`tus: cannot fetch \`file.uri\` as Blob, make sure the uri is correct and accessible. ${err}`
)
})
try {
const blob = await uriToBlob(input.uri)
return new FileSource(blob)
} catch (err) {
throw new Error(
`tus: cannot fetch \`file.uri\` as Blob, make sure the uri is correct and accessible. ${err}`
)
}
}

// Since we emulate the Blob type in our tests (not all target browsers
Expand Down
28 changes: 12 additions & 16 deletions lib/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -945,22 +945,18 @@ function openRequest(method, url, options) {
*
* @api private
*/
function sendRequest(req, body, options) {
const onBeforeRequestPromise =
typeof options.onBeforeRequest === 'function'
? Promise.resolve(options.onBeforeRequest(req))
: Promise.resolve()

return onBeforeRequestPromise.then(() => {
return req.send(body).then((res) => {
const onAfterResponsePromise =
typeof options.onAfterResponse === 'function'
? Promise.resolve(options.onAfterResponse(req, res))
: Promise.resolve()

return onAfterResponsePromise.then(() => res)
})
})
async function sendRequest(req, body, options) {
if (typeof options.onBeforeRequest === 'function') {
await options.onBeforeRequest(req)
}

const res = await req.send(body)

if (typeof options.onAfterResponse === 'function') {
await options.onAfterResponse(req, res)
}

return res
}

/**
Expand Down

0 comments on commit 01d3948

Please sign in to comment.