Browse Source

utils: accept sync functions in `wrapPromiseFunction()` (#1910)

* utils: add failing test for wrapPromiseFunction(syncFn)

* utils: promisify non-promise-returning functions in wrapPromiseFunction()
Renée Kooi 5 năm trước cách đây
mục cha
commit
0f269fc054

+ 8 - 1
packages/@uppy/utils/src/RateLimitedQueue.js

@@ -99,7 +99,14 @@ module.exports = class RateLimitedQueue {
     return (...args) => new Promise((resolve, reject) => {
       const queuedRequest = this.run(() => {
         let cancelError
-        fn(...args).then((result) => {
+        let promise
+        try {
+          promise = Promise.resolve(fn(...args))
+        } catch (err) {
+          promise = Promise.reject(err)
+        }
+
+        promise.then((result) => {
           if (cancelError) {
             reject(cancelError)
           } else {

+ 12 - 0
packages/@uppy/utils/src/RateLimitedQueue.test.js

@@ -44,4 +44,16 @@ describe('RateLimitedQueue', () => {
       expect(pending).toBe(0)
     })
   })
+
+  it('should accept non-promise function in wrapPromiseFunction()', () => {
+    const queue = new RateLimitedQueue(1)
+    function syncFn () { return 1 }
+    const fn2 = queue.wrapPromiseFunction(syncFn)
+
+    return Promise.all([
+      fn2(), fn2(), fn2(), fn2(),
+      fn2(), fn2(), fn2(), fn2(),
+      fn2(), fn2()
+    ])
+  })
 })