Is there any other way to implement a “listening” function without an infinite while loop?

后端 未结 2 1491
孤城傲影
孤城傲影 2020-12-06 09:04

I\'ve been thinking a lot about code and libraries like React that automatically, well, react to events as they happen, and was wondering about how all of that is implemente

2条回答
  •  独厮守ぢ
    2020-12-06 09:16

    "listeners" and "subscriptions" are just ideas. Everything can be abstracted with lambdas. Here is one possible implementation -

    const logger =
      // create a new "listener",
      // send any data we "hear" to console.log
      listen(console.log)
    
    // implement so-called "listener"
    const listen = (responder) =>
      x => (responder(x), x)
    
    // run it synchronously
    logger(1)
    logger(2)
    
    // or asynchronously
    setTimeout(_ => logger(3), 2000)
    
    // 1
    // 2
    // some time later...
    // 3

    So let's say we have a

提交回复
热议问题