Node.js Asynchronous Library Comparison - Q vs Async

前端 未结 3 1337
梦谈多话
梦谈多话 2020-12-08 07:35

I have used kriskowal\'s Q library for a project (web scraper / human-activity simulator) and have become acquainted with promises, returning them and resolving/rejecting th

3条回答
  •  一整个雨季
    2020-12-08 08:07

    Callback pyramids in your code can be simplified using promise composition and javascript lexical scoping.

    removeItem: function (itemId) {
    
      var removeRegexp = new RegExp('\\/stock\\.php\\?remove=' + itemId);
      var found = false
      var promise = getPage('/sock.php')
    
      _.times(5, (i) => {
        promise = promise.then((webpage) => {
          if (found) return true
          var removeMatch = webpage.match(removeRegexp)
          var found = removeMath !== null
          var nextPage = found ? removeMatch[0] : '/stock.php?p='+i+1
          return Q.delay(1000).then(() => this.getPage(nextPage))
        })
      })
    
      return promise.fail(console.log.bind(console))
    
    },
    

    IMHO async should not be used in new javascript code. Promises are more composable, and allow for a lot more intutive code.

    The primary reason why node did not use promises was because of performance concerns which have largely been addressed very well by libraries like Bluebird and Q.

    As async/await syntax becomes more mainstream, promises will pave the way for code that looks very similar with synchronous code.

提交回复
热议问题