Skip to content

Commit

Permalink
Merge pull request #1307 from lindapaiste/fix/callback-rejection
Browse files Browse the repository at this point in the history
Bug fix: `callCallback` should reject the returned Promise
  • Loading branch information
joeyklee authored Mar 7, 2022
2 parents fb1ded3 + 552d16d commit af1e447
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions src/utils/callcallback.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,38 @@
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT


/**
* Most ml5 methods accept a callback function which will be
* called with the arguments (error, result).
*
* Generic type T describes the type of the result.
* @template T
* @callback ML5Callback<T>
* @param {unknown} error - any error thrown during the execution of the function.
* @param {T} [result] - the expected result, if successful.
* @return {void} - callbacks can have side effects, but should not return a value.
*/

/**
* Generic type T describes the type of the result, ie. the value that the Promise will resolve to.
* @template T
* @param {Promise<T>} promise - the Promise to resolve.
* @param {ML5Callback<T>} [callback] - optional callback function to be called
* with the result or error from the resolved Promise.
* @return {Promise<T>} - returns the underlying Promise, which may be rejected.
*/
export default function callCallback(promise, callback) {
if (callback) {
if (!callback) return promise;
return new Promise((resolve, reject) => {
promise
.then((result) => {
callback(undefined, result);
return result;
resolve(result);
})
.catch((error) => {
callback(error);
return error;
reject(error);
});
}
return promise;
});
}

0 comments on commit af1e447

Please sign in to comment.