promise问题
怎么我的代码先打印‘download over’,后执行下载呢???
function downloadAsync(url, name) {
return new Promise(function(resolve, reject) {
request(url, function(err, response, body) {
if (err) {
reject(err);
} else {
fs.writeFileSync(path.resolve(process.cwd(), 'downloaded_html', name), body);
console.log('got ' + url);
resolve();
}
})
})
}
var urls = ['url1', 'url2', 'url3']
var promises = urls.map(function(url, i) {
var name = i + '.html'
downloadAsync(url, name)
})
Promise.all(promises).then(function() {
console.log('download over')
})
4 回复
var promises = urls.map(function(url, i) {
var name = i + '.html'
return downloadAsync(url, name)
})
加个return就好了
用箭头函数,可以省略 return
var promises = urls.map((url, i) => downloadAsync(url, i + '.html'))
Array.prototype.map 的并发是 Infinity, 要控制并发可以使用
- promise.map https://github.com/magicdawn/promise.map
- bluebird 提供的 Promise.map 支持一个 concurrency 参数,表示并发