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

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

3 回复
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); }); });

将以下代码拷贝到chrome的console里敲回车执行,如果你需要依次,将.all 换成 .series async function main(){ var urls = [‘https://www.baidu.com/a.html’,‘https://www.baidu.com/b.html’,'https://www.baidu.com/c.html’]; var tasks = []; urls.forEach(url=>{ tasks.push(fetch(‘https://www.baidu.com/s?wd=nba’,{method:'POST’})); }); var respArr = await Promise.all(tasks); var textArr = await Promise.all(respArr.map(resp=> resp.text())); textArr.forEach(text=> console.log(text)); } main();

回到顶部