谁能帮我用promise写一个例子?需求是依次请求三个URL,并把请求结果依次输出
发布于 3 天前 作者 zhishaofei3 170 次浏览 来自 问答

需求是依次请求三个URL,并把请求结果依次输出 http://baidu.com/a.html http://baidu.com/b.html http://baidu.com/c.html

2 回复
var Promise = require('bluebird'),
    rp = require('request-promise');
var urls = [
  'http://baidu.com/a.html',
  'http://baidu.com/b.html',
  'http://baidu.com/c.html'
]
Promise.mapSeries(urls, function(url){
  return rp({
    uri: url
  });
}).then(function(results){

});

试下看: const http = require(‘http’);

let getURL = function(url) { return new Promise(function(resolve, reject) { http.get(url, function(res) { let html = ‘’; res.on(‘data’, function(chunk) { html += chunk; }); res.on(‘end’, function() { resolve(html); }); res.on(‘error’, function(err) { reject(err); }); }); }); };

let urls = [ ‘http://baidu.com/a.html’, ‘http://baidu.com/b.html’, ‘http://baidu.com/c.html’];

let res = Promise.resolve();

urls.forEach(function(url) { res = res.then(function(res) { return getURL(url).then(console.log); }); });

回到顶部