{ "data": { "question": { "questionId": "2788", "questionFrontendId": "2650", "boundTopicId": null, "title": "Design Cancellable Function", "titleSlug": "design-cancellable-function", "content": "
Sometimes you have a long running task, and you may wish to cancel it before it completes. To help with this goal, write a function cancellable
that accepts a generator object and returns an array of two values: a cancel function and a promise.
You may assume the generator function will only yield promises. It is your function's responsibility to pass the values resolved by the promise back to the generator. If the promise rejects, your function should throw that error back to the generator.
\n\nIf the cancel callback is called before the generator is done, your function should throw an error back to the generator. That error should be the string "Cancelled"
(Not an Error
object). If the error was caught, the returned promise should resolve with the next value that was yielded or returned. Otherwise, the promise should reject with the thrown error. No more code should be executed.
When the generator is done, the promise your function returned should resolve the value the generator returned. If, however, the generator throws an error, the returned promise should reject with the error.
\n\nAn example of how your code would be used:
\n\n\nfunction* tasks() {\n const val = yield new Promise(resolve => resolve(2 + 2));\n yield new Promise(resolve => setTimeout(resolve, 100));\n return val + 1; // calculation shouldn't be done.\n}\nconst [cancel, promise] = cancellable(tasks());\nsetTimeout(cancel, 50);\npromise.catch(console.log); // logs "Cancelled" at t=50ms\n\n\n
If instead cancel()
was not called or was called after t=100ms
, the promise would have resolved 5
.
\n
Example 1:
\n\n\nInput: \ngeneratorFunction = function*() { \n return 42; \n}\ncancelledAt = 100\nOutput: {"resolved": 42}\nExplanation:\nconst generator = generatorFunction();\nconst [cancel, promise] = cancellable(generator);\nsetTimeout(cancel, 100);\npromise.then(console.log); // resolves 42 at t=0ms\n\nThe generator immediately yields 42 and finishes. Because of that, the returned promise immediately resolves 42. Note that cancelling a finished generator does nothing.\n\n\n
Example 2:
\n\n\nInput:\ngeneratorFunction = function*() { \n const msg = yield new Promise(res => res("Hello")); \n throw `Error: ${msg}`; \n}\ncancelledAt = null\nOutput: {"rejected": "Error: Hello"}\nExplanation:\nA promise is yielded. The function handles this by waiting for it to resolve and then passes the resolved value back to the generator. Then an error is thrown which has the effect of causing the promise to reject with the same thrown error.\n\n\n
Example 3:
\n\n\nInput: \ngeneratorFunction = function*() { \n yield new Promise(res => setTimeout(res, 200)); \n return "Success"; \n}\ncancelledAt = 100\nOutput: {"rejected": "Cancelled"}\nExplanation:\nWhile the function is waiting for the yielded promise to resolve, cancel() is called. This causes an error message to be sent back to the generator. Since this error is uncaught, the returned promise rejected with this error.\n\n\n
Example 4:
\n\n\nInput:\ngeneratorFunction = function*() { \n let result = 0; \n yield new Promise(res => setTimeout(res, 100));\n result += yield new Promise(res => res(1)); \n yield new Promise(res => setTimeout(res, 100)); \n result += yield new Promise(res => res(1)); \n return result;\n}\ncancelledAt = null\nOutput: {"resolved": 2}\nExplanation:\n4 promises are yielded. Two of those promises have their values added to the result. After 200ms, the generator finishes with a value of 2, and that value is resolved by the returned promise.\n\n\n
Example 5:
\n\n\nInput: \ngeneratorFunction = function*() { \n let result = 0; \n try { \n yield new Promise(res => setTimeout(res, 100)); \n result += yield new Promise(res => res(1)); \n yield new Promise(res => setTimeout(res, 100)); \n result += yield new Promise(res => res(1)); \n } catch(e) { \n return result; \n } \n return result; \n}\ncancelledAt = 150\nOutput: {"resolved": 1}\nExplanation:\nThe first two yielded promises resolve and cause the result to increment. However, at t=150ms, the generator is cancelled. The error sent to the generator is caught and the result is returned and finally resolved by the returned promise.\n\n\n
Example 6:
\n\n\nInput: \ngeneratorFunction = function*() { \n try { \n yield new Promise((resolve, reject) => reject("Promise Rejected")); \n } catch(e) { \n let a = yield new Promise(resolve => resolve(2));\n let b = yield new Promise(resolve => resolve(2)); \n return a + b; \n }; \n}\ncancelledAt = null\nOutput: {"resolved": 4}\nExplanation:\nThe first yielded promise immediately rejects. This error is caught. Because the generator hasn't been cancelled, execution continues as usual. It ends up resolving 2 + 2 = 4.\n\n
\n
Constraints:
\n\ncancelledAt == null or 0 <= cancelledAt <= 1000
generatorFunction returns a generator object
Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES6 features.
lodash.js library is included by default.
\\r\\n\\r\\nFor Priority Queue / Queue data structures, you may use 5.3.0 version of datastructures-js/priority-queue and 4.2.1 version of datastructures-js/queue.
\"], \"typescript\": [\"Typescript\", \"TypeScript 4.5.4, Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES2020 features.
lodash.js library is included by default.
\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }