还有另一种方法可以在 .map() 中添加道具和 return 对象
Is there another way to add a prop and return object within .map()
这有点不错,但有点令人困惑,因为我必须打开承诺和 return 项目。
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
})
})
您或许可以将代码缩减为一张地图。
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
})
})
});
你可以让它看起来更好看,但总的来说没问题:
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));
这有点不错,但有点令人困惑,因为我必须打开承诺和 return 项目。
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
})
})
您或许可以将代码缩减为一张地图。
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
})
})
});
你可以让它看起来更好看,但总的来说没问题:
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));