I am trying to create a small application that closes over the delay
function and defines a new function using a callback and a wait time. I then wanted to use this newly created inner setTimeout
function to take a single parameter that would be run on the callback after the wait time.
function addTwo(num) { return num + 2 } const delay = (callback, wait) => { return setTimeout((value) => callback(value), wait) } var delayAddByTwo = delay(addTwo, 100) console.log(delayAddByTwo(6)) // expected result 8 // actual result --- Uncaught TypeError: delayAddByTwo is not a function
As far as I can tell after the delayAddByTwo = delay(addTwo, 100)
the only parameter left to create is the value
passed to callback inside the 'inner' setTimeOut
function. What am I missing about closure in this example?
You need to replace var delayAddByTwo = delay(addTwo, 100)
by var delayAddByTwo = (num) => { delay(() => {addTwo(num)}, 100);}
function addTwo(num) { console.log(num + 2) return num + 2 } const delay = (callback, wait) => { setTimeout(callback, wait) } var delayAddByTwo = (num) => { delay(() => {addTwo(num)}, 100); } console.log(delayAddByTwo) delayAddByTwo(6) // expected result 8 // actual result --- Uncaught TypeError: delayAddByTwo is not a function
Change
var delayAddByTwo = delay(addTwo, 100)
To
const delayAddByTwo = delay => (addTwo, 100)
You need to make delay return another function which accepts n
. This n
represents the number which will be passed into addTwo
(ie the callback). setTimeout
by default will return its timeoutID
, so, instead, you can return a Promise , which resolves to the result of calling addTwo
with n
. In order to get your result from the Promise, you can await
it within an async
function .
See example below:
const addTwo = num => num + 2; const delay = (callback, wait) => n => new Promise(res => setTimeout(res, wait, callback(n))); (async () => { const delayAddByTwo = delay(addTwo, 1000); const res = await delayAddByTwo(6); console.log(res); })();
Above I have used the third argument of setTimeout
, which will be used as the first argument of the callback and passed to res
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.