software-tools-books / js4ds

JavaScript for Data Science
https://third-bit.com/js4ds/
Other
187 stars 32 forks source link

Possible issue in exercise "Empty Promises" #221

Open jerrylususu opened 3 years ago

jerrylususu commented 3 years ago

In the section "Promises", there is a exercise named "Empty Promises". I tried to fill the blanks, and I was able to get the desired result. However, the execution time is much faster than expected. It seems that the setTimeout is returning instantly. Here is my code.

const makePromise = (someInteger) => {
  return new Promise((resolve, reject) => {
    setTimeout(resolve(someInteger), someInteger * 1000)
  })
}

Promise.all([makePromise(7), makePromise(8), makePromise(2),
             makePromise(6), makePromise(5)]).then(
  numbers => console.log(numbers))

After some digging, I found that the problem seems to be in the invocation of resolve(someInteger). When calling setTimeout, this part will be evaluated, thus the promises will be returned immediately. One possible fix is using Function.Prototype.bind to wrap, as shown below:

-  setTimeout(resolve(someInteger), someInteger * 1000)
+  setTimeout(resolve.bind(null,someInteger), someInteger * 1000)

The exercise only allows the blanks to be filled, but I can not find a way to resulting in the desired execution (wait up to 8 sec) without changing other code. Thus I doubt that there might possibly be an issue here.

Source: javascript - How can I pass a parameter to a setTimeout() callback? - Stack Overflow