是否有另一种方法在.map()中添加prop和return对象

时间:2015-01-14 22:46:49

标签: javascript promise bluebird

这很好,但是有点混乱,因为我必须打开承诺并退回物品。

Promise.map(assets, function(asset){
  asset.download_path = path.join(downloadDir, asset.name)
  return existsAsync(asset.download_path).then(function(exists){
    asset.exists = exists
    return asset;
  })
}).map(function(asset){
  if(asset.exists) return asset
  return downloadStream(asset.browser_download_url, asset.download_path).then(function(download){
    return asset
  })
})

2 个答案:

答案 0 :(得分:2)

你可以让它看起来更漂亮,但一般情况下它很好:

return Promise.map(assets, function(asset){
  return existsAsync(path.join(downloadDir, asset.name));
}).map(function(ex, i){ 
    if(ex) return assets[i];
    return downloadStream(assets[i].downloadUrl, assets[i].downloadPath).return(assets[i]);
});

或者,使用ex6语法:

import map from Promise

let exists = map(assets, a => existsAsync(path.join(downloadDir, a.name));
let download = a => downloadStream(a.downloadUrl, a.downloadPath).return(a);
return map(exists, (ex, i) => ex ? assets[i] : download(asset));

答案 1 :(得分:1)

您可以将代码缩减为单个地图。

Promise.map(assets, function(asset){
  asset.download_path = path.join(downloadDir, asset.name)
  return existsAsync(asset.download_path).then(function(exists){
    asset.exists = exists
    if(exists){
      return asset;
    }
    return downloadStream(asset.browser_download_url, asset.download_path).then(function(download){
      return asset
    })
  })
});