Promise Time Limit - Leetcode 2637 - JavaScript 30-Day Challenge

NeetCodeIO · Beginner ·⚡ Algorithms & Data Structures ·3y ago

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 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

This video teaches how to solve 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. The video also modifies the code to use async/await keywords and traditional try-catch error handling methods.

Key Takeaways
  1. Call the function with arguments
  2. Define a custom promise to stop execution after a certain time limit
  3. Use set timeout to execute a function after a certain time limit
  4. Handle reject and resolve cases in promises
  5. Use then() callback to wait for asynchronous function to complete
  6. Use finally() method to handle cleanup after promise is resolved or rejected
  7. Use clearTimeout() to cancel scheduled timeout
  8. Comment out piece of code
  9. Clean up code
  10. Use async/await keywords
💡 Using promises and async programming can help implement rate limits for functions and prevent time limit exceeded errors, and modifying code to use async/await keywords can simplify asynchronous programming.

Related Reads

📰
Data Structures & Algorithms for Mobile App Developers
Learn essential data structures and algorithms for mobile app development to improve performance and efficiency
Medium · Programming
📰
Data Structures and Algorithms Deep‑Dive — Real-world Applications of Hash Tables (Chapter 3…
Learn how hash tables are used in real-world applications and improve your coding skills with practical examples
Medium · Programming
📰
Data Structures and Algorithms Deep‑Dive — Real-world Applications of Hash Tables (Chapter 3…
Learn how hash tables are applied in real-world scenarios and improve your coding skills with practical examples
Medium · Python
📰
Day 29/100 Koko Eating Bananas (Binary Search)
Learn to implement binary search to solve the Koko Eating Bananas problem and improve your algorithmic skills
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)
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →