2017-06-22 30 views
0

我想运行gplp任务,请求api终端并监视响应的变化,检测到变化后,gulp将运行build任务。观看gulp http响应的变化

为了实现它,我创建了一个任务手表文件,请求响应体:运行API请求

gulp.task('watch-response', function() { 
    gulp.watch('response_file', function() { 
     gulp.start('build'); 
    }); 
}); 

而且一个任务,解析响应身体JSON,并将其保存在文件response_file

request = require('request'), 
fs = require('fs'); 

gulp.task('api_request', function() { 
    request('www.api.com/endpoint', function(error, response, body) { 
     var hash = JSON.parse(body).hash; 
     fs.writeFileSync('response_file', hash); 
    }); 
}); 

这里的问题是,我想运行在一些延迟循环api_request任务,所以API将不断提出要求。我尝试在while(true)循环中运行它,但它出错了。

回答

1

可以使用setTimeout,就像这一点,那么就会在循环作品与一些延迟:

gulp.task('api_request', function() { 
     var delay = 1000; 
     function const_request(){ 
     request('www.api.com/endpoint', function(error, response, body) { 
      var hash = JSON.parse(body).hash; 
      fs.writeFileSync('response_file', hash); 
      setTimeout(const_request, delay); 
     }); 
     } 
    const_request(); 
    }); 
+0

感谢简单而明确的递归的解决方案! :) – strongBAD

+0

不客气! – sunt