Promise Time Limit - Leetcode 2637 - JavaScript 30-Day Challenge
Key Takeaways
The video solves Leetcode 2637 using JavaScript, applying knowledge of promises and async programming to implement a rate limit for a function and prevent time limit exceeded errors. It covers using promises to handle asynchronous execution and timeouts, defining custom promises, and handling reject and resolve cases.
Full Transcript
hey everyone welcome back and let's write some more neat code today so today let's solve the problem promise time limit day 12 of the JavaScript challenge we're given an asynchronous function FN and a time limit in milliseconds and we just want to return a Time limited version of this function so this problem is actually pretty understandable and pretty practical basically we want to have some kind of time out similar to kind of how leak code implements time limit exceeded where if some piece of code in this case this function that's passed in executes longer than some time threshold then we don't want it to execute forever like who knows maybe there's an infinite Loop somewhere in there or an API call that's just taking forever and all we want to do is put some time limit on it they also mentioned that it should reject with a string not an error I'll get into that in just a second basically they mentioned that because in Practical terms usually when some error occurs we want to return like an error object in JavaScript script which you can then pass in some string in our case time limit exceeded and this is a concept from pretty much every programming language but basically an error object is used to just encapsulate a bit more information like in this case we have the error name which basically refers to the type in this case this is just a pretty generic error but we can get more specific like depending on what type of error occurred but these are runtime errors typically and in this case this string that we passed in would be the error Dot message and actually just to prove it to you let me run this piece of code so here I'm going to console log the error name as well as the message and running it we see that we get what we expected okay back to the problem first let's take a quick look at how our code is going to be used because then the problem is pretty simple to understand basically we are creating this time limit function we are given some boilerplate but basically time limit will accept a function in this case this is our function and actually just to make it more readable why not redefine it up over here I'm going to not make it an arrow function I'm going to maybe just call it f or rather FN because that's kind of what we're using here so then we're passing in FN down here and this is going to be an asynchronous function in this case we don't really care about the implementation but we know that every single asynchronous function does end up returning a promise now at first you might think we need to put the async keyword here and yes we definitely could but it's actually not necessary functions are allowed to return promises without the async keyword I know that might be a little bit confusing for beginners but the main reason we use async at all is usually because we want to call a weight inside of the async function in this case we don't really need to do that so we don't really need to Define this as an async function but this is the function we pass in here and in this case it can only run for a maximum of 100 milliseconds and the return value of this is the limited function this is not a value this is a function because remember when we call time limit it returns a function here that we can then call with some value in this case we pass in 150 what does that mean well here's the variable and basically it's calling set timeout and waiting 150 seconds before this promise resolves but remember we limit it to a hundred milliseconds so of course in this case it's going to time out before the actual function here is complete so in this case we catch the error and we console log it and we expect time limit exceeded to be returned so this is our job we have to implement this rate limit up here so now let's actually get into that first of all what is going to be the return value of this function well it's an async function so they kind of gave us a hint that for sure we have to return a promise as a beginner the first thing you might have thought is we have to call this function and you technically are right yes we're gonna have to call this function and yes we are going to have have to pass in these arguments into our function over here but we don't necessarily need to return this I mean technically doing this also does return a promise because remember this function is always going to be asynchronous so it's always going to return a promise but in this case how would we time limit it pretty much the only way we know how to set timeouts is with the set timeout function and that will work in this case how would we want to call set timeout remember this parameter second parameter T is going to be the timeout threshold that's usually the second parameter for set timeout but what would we want to do in this case well we would want to stop the execution of this function If This Were to be called what can we do to achieve that well the hint is we have to return a promise here and Promises can do exactly that remember promises can either resolve or reject and then they are no longer pending so we have to in our case create a custom prom Thomas which honestly shouldn't be too difficult because in yesterday's video we went pretty deep into promises now remember a promise accepts a function with two parameters resolve and reject which are methods that we are going to call within this callback this function right off the bat I'm just going to say we're going to call reject with that string that they told us about time limit exceeded it's not like we want to immediately execute this promise and immediately reject it we only want to do that after this much time has passed and that's what the first parameter of set timeout is so this is what you might do to handle that rejection case put this and pass it as the first parameter but there's a bug here and you would be able to catch that bug probably in typescript I don't know if we would with the boilerplate that they give us for typescript but in general this is the type of bug that typescript will catch for you and it's a bug I've made many times as a beginner remember the set timeout first parameter accepts a method not of value in this case we are calling reject that's not what we want to do we want to pass in a method that calls reject so we could Define like a separate method that we'll call this piece of code or the easiest thing that most people do in this case is just have an anonymous function like this we don't need any parameters but this is a function this isn't a value we're not even executing this function we're just passing this function in and telling set timeout execute this piece of code after this much time so that's great probably we do need to call our function here so let's take this and cut it and move it up here one thing to notice is we are returning the return value of the function call that's usually a normal thing to do but in Promised Land inside of the promise callback we don't really care about return values we don't need this and it doesn't have any significance for us we only care about whether This Promise has been resolved or rejected we handled the rejection case and to handle the resolve case you might think just take the return value of this guy and call resolve but remember we are doing asynchronous programming this is another beginner mistake to make the way this code would execute is immediately set the timeout not necessarily executing this but then it would immediately execute this code and resolve is not an asynchronous function it's just going to call resolve and completely end the promise even though this asynchronous function has not finished executing so we don't want to do that we want to wait for this function to actually be complete how do you do that in Promised Land well remember the then callback accepts a method and in this case we can again write an anonymous method which will maybe get that response value that we get from this function or maybe it doesn't return a response in which case this would be undefined but whatever it is we then want to call our resolve only at after this is actually finished it's technically possible though that there could be an error thrown so let's handle the case where there is and I think this is actually required in this problem I forgot to do it the first time and I got rejected so we have the error it could be undefined it could be empty who knows regardless we want to call reject and pass the error in which reminds me we should probably pass the response in to resolve up here as well now this is pretty much the solution both of these functions are asynchronous so the callbacks that we pass in may not necessarily execute immediately But whichever one finishes first is the one that is going to resolve or reject the promise now while this code will get accepted on leak code there's a quick thing worth mentioning that they mentioned in the editorial and that is that it's possible that this function completes and then the promise is resolved but the way JavaScript Works immediately when set timeout is called this function is scheduled to run by JavaScript I think it's added to the event queue but I'm not sure on the details because this one is actually time limited so it may work a little bit differently than this but the idea is that this is actually going to execute this callback no matter what after this period of time even if the promise has already been resolved that doesn't mean the promise can be resolved and then later be rejected because once it's been resolved the promise is complete we can't really do anything anymore inside of the promise but it does kind of act as a memory leak like if we set a bunch of these set timeouts like a thousand of them and these never really needed to be executed they were still in memory anyway and then after some period of time they do end up being executed it's kind of a waste of our system resources so the easiest way to fix that is set timeout returns an ID and we can use that ID to clear the time out so we can call something called clear timeout which will basically unschedule this task or this method to run after that period of time and all we have to pass in is the ID of that again this this is a bug the way this code is going to execute this will execute schedule something this will schedule something and this will actually clear the time out we only want to clear the timeout after this function has been completed so we could move this into the then block probably we also want to move this into the catch block but why move it into both of these blocks if there's actually a built-in method in promises called finally which handles that for us and we don't even need the return value in that case we could just take this cut and paste it up above so this is the most complete code for the first solution I'm going to show you let's run it to make sure that it works and as you can see yes it does but there is a small modification we can make to this code to take advantage of the away async keywords that we learned about yesterday so what I'm going to do is just comment out this piece of code because the rest we can actually reuse and I'll clean things up a tad bit so here how can we take advantage of a sync wait what's the whole point well it's basically another way of writing this code down here we want to wait for this to finish before we can resolve so the idea is we have the await keyword we call this asynchronous function passing in the same parameters and only after this promise has resolved or rejected then will the next line of code now execute this is the type of programming you're probably used to and honestly this solution is probably easier for you to understand if you're new to this type of programming but remember this could throw an error or it could be successful and we want to handle both cases so we can use the traditional try catch error handling method where let's say the error is called that and then let's move this up into the try block and in the catch block we will reject the promise if an error is thrown with whatever this error happens to be but I don't think this part of code is actually being executed in this example but I'm not 100 sure one thing I am probably messing up though is this result is not defined so let's actually Define it here so if we didn't have the await keyword here this would return a promise but we don't want to resolve with a promise we want the actual value so we want to wait for the promise to actually be resolved there is a small bug here though remember awake can only be used in asynchronous functions where is the function block that this code is being executed inside well these curly braces I know it's kind of hard to read at least for me this is our function here these are the parameters that the function is taking and functions have to be defined with the async keyword and for anonymous functions we can add that as well just like this so now I believe this code is bug free but let's test it and see if it is and thankfully it is if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io thanks for watching and I'll see you soon
Original Description
Solving Day 12 of the Leetcode 30-day javascript challenge. Today we get a chance to apply our knowledge of promises and async programming that we learned in yesterday's video.
🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews
🥷 Discord: https://discord.gg/ddjKRXPqtk
🐦 Twitter: https://twitter.com/neetcode1
🐮 Support the channel: https://www.patreon.com/NEETcode
⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf
💡 DYNAMIC PROGRAMMING PLAYLIST: https://www.youtube.com/watch?v=73r3KWiEvyk&list=PLot-Xpze53lcvx_tjrr_m2lgD2NsRHlNO&index=1
Problem Link: https://leetcode.com/problems/promise-time-limit/
0:00 - Read the problem
0:45 - What is an error?
1:40 - Read example
3:35 - Solution one (using callback)
10:38 - Solution two (using async/await)
leetcode 2637
#neetcode #leetcode #python
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from NeetCodeIO · NeetCodeIO · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
Design Linked List - Leetcode 707 - Python
NeetCodeIO
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
LFU Cache - Leetcode 460 - Python
NeetCodeIO
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
IPO - Leetcode 502 - Python
NeetCodeIO
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
Sort an Array - Leetcode 912 - Python
NeetCodeIO
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO
Related Reads
📰
📰
📰
📰
Data Structures & Algorithms for Mobile App Developers
Medium · Programming
Data Structures and Algorithms Deep‑Dive — Real-world Applications of Hash Tables (Chapter 3…
Medium · Programming
Data Structures and Algorithms Deep‑Dive — Real-world Applications of Hash Tables (Chapter 3…
Medium · Python
Day 29/100 Koko Eating Bananas (Binary Search)
Medium · Programming
Chapters (5)
Read the problem
0:45
What is an error?
1:40
Read example
3:35
Solution one (using callback)
10:38
Solution two (using async/await)
🎓
Tutor Explanation
DeepCamp AI