Joh*_*nyb 5 javascript node.js promise
我正在做nodechool练习,
此问题与上一个问题(HTTP COLLECT)相同,因为您需要使用http.get().但是,这次您将获得三个URL作为前三个命令行参数.
您必须收集每个URL提供给您的完整内容,并将其打印到控制台(stdout).您不需要打印长度,只需将数据打印为String; 每个网址一行.问题是您必须按照与作为命令行参数提供的URL相同的顺序打印它们.
换句话说,我要注册3个http.get请求,并按顺序打印从中收到的数据.
我试图用promises做另外一个get请求不会被调用直到第一个没有结束.
我的代码看起来像这样
var http=require("http");
var collect=[];
var dat=[];
for( var i = 2 ; i < process.argv.length;i++){
collect.push(process.argv[i]);
}
function chainIt(array,callback){
return array.reduce(function(promise,item){
return promise.then(function(){
return callback(item)
})
},Promise.resolve())
}
function getIt(item){
return http.get(item,function(response){
response.on("data",function(data){
dat.push(data);
})
})
}
chainIt(collett,function(item){
return getIt(item)
})
}).then(function(){
collect.forEach(function(x){
console.log(x);
})
})
Run Code Online (Sandbox Code Playgroud)
但我实际上没有打印数据=我没有通过练习.
我没有看到任何错误,但我只是从promises和node开始.哪里出错了?
对于教育目的,我最近写了一个包装http,并https使用本机模块Promise秒.也就是说,我建议使用一个库,这样的request; 这使事情更简单,具有单元测试覆盖率,由开源社区维护.此外,我的包装器与响应块进行了一个天真的字符串连接,我不相信这是建立响应主体的最高效方式.
仅供参考:这需要Node.js 4或更高版本,尽管Node 0.xx中的方法几乎相同
'use strict';
const http = require('http');
const url = require('url');
module.exports = {
get(url) {
return this._makeRequest('GET', url);
},
_makeRequest(method, urlString, options) {
// create a new Promise
return new Promise((resolve, reject) => {
/* Node's URL library allows us to create a
* URL object from our request string, so we can build
* our request for http.get */
const parsedUrl = url.parse(urlString);
const requestOptions = this._createOptions(method, parsedUrl);
const request = http.get(requestOptions, res => this._onResponse(res, resolve, reject));
/* if there's an error, then reject the Promise
* (can be handled with Promise.prototype.catch) */
request.on('error', reject);
request.end();
});
},
// the options that are required by http.get
_createOptions(method, url) {
return requestOptions = {
hostname: url.hostname,
path: url.path,
port: url.port,
method
};
},
/* once http.get returns a response, build it and
* resolve or reject the Promise */
_onResponse(response, resolve, reject) {
const hasResponseFailed = response.status >= 400;
var responseBody = '';
if (hasResponseFailed) {
reject(`Request to ${response.url} failed with HTTP ${response.status}`);
}
/* the response stream's (an instance of Stream) current data. See:
* https://nodejs.org/api/stream.html#stream_event_data */
response.on('data', chunk => responseBody += chunk.toString());
// once all the data has been read, resolve the Promise
response.on('end', () => resolve(responseBody));
}
};
Run Code Online (Sandbox Code Playgroud)
编辑:我只是意识到你是新手Promise.以下是如何使用此包装器的示例:
'use strict';
const httpService = require('./httpService'); // the above wrapper
// get one URL
httpService.get('https://ron-swanson-quotes.herokuapp.com/v2/quotes').then(function gotData(data) {
console.log(data);
});
// get multiple URLs
const urls = [
'https://ron-swanson-quotes.herokuapp.com/v2/quotes',
'http://api.icndb.com/jokes/random'
];
/* map the URLs to Promises. This will actually start the
* requests, but Promise.prototype.then is always called,
* even if the operation has resolved */
const promises = urls.map(url => httpService.get(url));
Promise.all(promises).then(function gotData(responses) {
/* responses is an array containing the result of each
* Promise. This is ordered by the order of the URLs in the
* urls array */
const swansonQuote = responses[0];
const chuckNorrisQuote = responses[1];
console.log(swansonQuote);
console.log(chuckNorrisQuote);
});
Run Code Online (Sandbox Code Playgroud)
Piy*_*gar -1
其中一种方法是使用“Q”库。
首先创建将命中 URL 并返回 Promise 的函数
var Q = require('q);
function getIt(item){
return http.get(item,function(response){
return Q.resolve(response); // Return response
OR
return Q.resolve(error); // Return error
})
})
}
var urls = ['url1','url2','url3']; // list of urls
Q.spread(urls.map(getIt))
.then(function(res1,res2,res3){
// res1 is response for url1 and on
//Once all calls are finished you will get results here
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14771 次 |
| 最近记录: |