Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug fix: callCallback should reject the returned Promise #1307

Merged
merged 2 commits into from
Mar 7, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
});
}