2015-08-20 4 views
1

Я пытаюсь проверить, является ли определенный объект (this) экземпляром потока. Мне сложно определить, действительно ли это оригинал this в глубине функции, как это было при срабатывании функции.Как проверить, является ли объект экземпляром stream.js?

Я пробовал typeof this, и он возвращает object. Я рассмотрел этот вопрос и не нашел ясного ответа .. какие-либо предложения? Благодаря, прежде

StreamName.prototype._getEndpointData = function (endpoint) { 
    /* 
    Make a request based on a specific endpoint 
    */ 
    var apikey = this.source.apikey; 

    request.getAsync({ 
     headers: { 
      // 'content-type' : 'application/x-www-form-urlencoded', 
      'User-Agent': 'request', 
      'Authorization': getAuthByApikey(apikey) 
     }, 
     url: generateUrl(apikey, endpoint) 
     }) 
     .get(1) // get the body 
     .then(function (body) { 
      if (body == 'Authentication Failed') { 
       throw new Error(body); 
      } 
      return body; 
     }) 
     .then(JSON.parse) 
     .then(function (body) { 
      if (body.status == 500) { 
       throw new Error(body.message || 'MailChimp API request error'); 
      } 

      // collections: lists, campaigns & reports 
      var collection = body[ endpoint ]; 

      for (var i in collection){ 
       var instanceEndpoint = endpoint + '/' + collection[i].id; 

       request.getAsync({ 
        headers: { 
         'User-Agent': 'request', 
         'Authorization': getAuthByApikey(apikey) 
        }, 
        url: generateUrl(apikey, instanceEndpoint) 
        }) 
        .get(1) // get the body 
        // .then(console.log) 
        .then(function (body) { 
         if (body == 'Authentication Failed') { 
           throw new Error(body); 
        } 
        return body; 
        }) 
        .then(JSON.parse) 
        .then(function (body) { 
         return body; 
        }) 
        .then(this.push.bind(this)) 
        // Getting an error Unhandled rejection TypeError: Cannot read property 'bind' of undefined 
        // IS 'THIS' as the same as it was at top of the function? 
        .then(this.push.bind(this, null)) 
        .catch(this.emit.bind(this, 'error')); 
      } 
     }) 
} 
+0

Вы можете разместить свой код? –

+0

@VsevolodGoloviznin добавлен код .. –

ответ

2

this здесь относится к request.getAsync

.then(this.push.bind(this, null)) 

Вы должны сохранить this ссылку на какой-либо переменной в начале функции, то вы можете обратиться к нему позже

StreamName.prototype._getEndpointData = function (endpoint) { 
    /* 
    Make a request based on a specific endpoint 
    */ 
    var apikey = this.source.apikey; 
    var _stream = this; 

    request.getAsync({ 
     headers: { 
      // 'content-type' : 'application/x-www-form-urlencoded', 
      'User-Agent': 'request', 
      'Authorization': getAuthByApikey(apikey) 
     }, 
     url: generateUrl(apikey, endpoint) 
     }) 
     .get(1) // get the body 
     .then(function (body) { 
      if (body == 'Authentication Failed') { 
       throw new Error(body); 
      } 
      return body; 
     }) 
     .then(JSON.parse) 
     .then(function (body) { 
      if (body.status == 500) { 
       throw new Error(body.message || 'MailChimp API request error'); 
      } 

      // collections: lists, campaigns & reports 
      var collection = body[ endpoint ]; 

      for (var i in collection){ 
       var instanceEndpoint = endpoint + '/' + collection[i].id; 

       request.getAsync({ 
        headers: { 
         'User-Agent': 'request', 
         'Authorization': getAuthByApikey(apikey) 
        }, 
        url: generateUrl(apikey, instanceEndpoint) 
        }) 
        .get(1) // get the body 
        // .then(console.log) 
        .then(function (body) { 
         if (body == 'Authentication Failed') { 
           throw new Error(body); 
        } 
        return body; 
        }) 
        .then(JSON.parse) 
        .then(function (body) { 
         return body; 
        }) 
        .then(_stream.push.bind(this)) 

        //should replace this with _stream 
        .then(_stream.push.bind(this, null)) 
        .catch(_stream.emit.bind(this, 'error')); 
      } 
     }) 
} 
1

Вы должны использовать instanceof оператор:

var stream = require('stream'); 
var isStream = this instanceof stream.Readable; 

хотя могут быть некоторые другие проблемы, связанные с этим, вы можете прочитать о них здесь: nodejs: Check if variable is readable stream