mirror of
https://github.com/NodeBB/NodeBB.git
synced 2025-10-26 08:36:12 +01:00
fix: properly wrap promise to callback-style function (#12030)
Async function xhr use a mixture of await and callback, which is not correct when an exception is thrown before callback happens. Use only async/await for it and create a new callback-style wrapper.
This commit is contained in:
@@ -27,16 +27,14 @@ function call(options, callback) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return reject(err);
|
return reject(err);
|
||||||
}
|
}
|
||||||
|
|
||||||
resolve(data);
|
resolve(data);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function xhr(options, cb) {
|
async function xhr_async(options) {
|
||||||
// Normalize body based on type
|
// Normalize body based on type
|
||||||
const { url } = options;
|
const { url } = options;
|
||||||
delete options.url;
|
delete options.url;
|
||||||
@@ -79,16 +77,20 @@ async function xhr(options, cb) {
|
|||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
if (response) {
|
if (response) {
|
||||||
return cb(new Error(isJSON ? response.status.message : response));
|
throw new Error(isJSON ? response.status.message : response);
|
||||||
}
|
}
|
||||||
return cb(new Error(res.statusText));
|
throw new Error(res.statusText);
|
||||||
}
|
}
|
||||||
|
|
||||||
cb(null, (
|
return isJSON && response && response.hasOwnProperty('status') && response.hasOwnProperty('response') ?
|
||||||
isJSON && response && response.hasOwnProperty('status') && response.hasOwnProperty('response') ?
|
response.response :
|
||||||
response.response :
|
response;
|
||||||
response
|
}
|
||||||
));
|
|
||||||
|
function xhr(options, callback) {
|
||||||
|
// then().catch() is not correct here because callback() is called twice when the first then() throws an exception.
|
||||||
|
// pass onfulfilled and onrejected here, as two parameters of Promise.prototype.then()
|
||||||
|
xhr_async(options).then(result => callback(null, result), error => callback(error));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function get(route, data, onSuccess) {
|
export function get(route, data, onSuccess) {
|
||||||
|
|||||||
Reference in New Issue
Block a user