promise问题
发布于 3 个月前 作者 postgetme 385 次浏览 来自 问答

怎么我的代码先打印‘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, 要控制并发可以使用

回到顶部