N
N
Nikita Gusakov2014-04-30 15:18:47
JavaScript
Nikita Gusakov, 2014-04-30 15:18:47

How to rewrite code using Promise/yield?

http = require 'http'

module.exports = class Request
  get: (url, cb) ->
    http.get url, (res) ->
      body = ''
      res.on 'data', (chunk) ->
        body += chunk.toString()
      res.on 'end', () ->
        cb.apply res, [body]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Pushkarev, 2014-04-30
@rock

yield just won't work, you need a helper spawn. And coffee does not support generators. Promise? Native ES6 - something in style

http = require 'http'

module.exports = class Request
  get: (url) ->
    new Promise (resolve, reject)->
      req = http.get url, (res) ->
        body = ''
        res.on 'data', (chunk) ->
          body += chunk.toString()
        res.on 'end', ->
          resolve body
      req.on 'error', reject

and use
require(ваш_модуль).get(ваш_url)
  .then (страница)->
  .catch (ошибка)->

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question