Issue
I was provided with this API:
function doSomeWork(callbacks : {
success ?: (result : SuccessCallbackResult) => void,
fail ?: (result : FailCallbackResult) => void,
complete ?: (result : CompleteCallbackResult) => void
}) : Task
With a simple wrapper, I got a function that returns a Promise
:
function doSomeWorkAsync() : Promise<SuccessCallbackResult> {
return new Promise((resolve, reject) => {
const callbacks = {
success: resolve,
fail: reject,
};
doSomeWork(callbacks);
});
}
But I lose the Task
returned by doSomeWork
in this way.
Can I wrap the API in some way that I can get both a Promise
and a Task
? Something like this:
function doSomeWorkAsync() : [Promise<SuccessCallbackResult>, Task] {
// implementation
}
And I need the Task
returned synchronously because I might need it to .abort()
itself.
Solution
Can I wrap the API in some way that I can get both a
Promise
and aTask
?
Yes, the new Promise
callback is executed synchronously:
function doSomeWorkAsync(): [Promise<SuccessCallbackResult>, Task] {
let task;
const promise = new Promise((success, fail) => {
task = doSomeWork({ success, fail });
});
return [promise, task];
}
(TypeScript may require a task as Task
assertion if it doesn't know that task
has been assigned before it is used)
Answered By - Bergi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.