在 node.js 链接中使用 if 条件

Using if condition in node.js chaining

关于 node.js 使用 sharp 库我们如何在链接条件中添加条件 我试着用这个。这样可以吗??

    S3.getObject({Bucket: BUCKET, Key: originalKey}).promise()
    .then(data => Sharp(data.Body)
    if(useCrop){
      .crop(width, height)
    }
    if(useResize){
      .resize(width, height)
    }
    .toFormat(setFormat)
    .withoutEnlargement(p_withoutEnlargement)
    .quality(quality)
    .max(max)
    .flatten()
    .toBuffer()
    )
    .then(buffer => S3.putObject({
      Body: buffer,
      Bucket: BUCKET,
      ContentType: 'image/'+setFormat,
      CacheControl: `max-age=${maxAge}`,
      Key: key,
    }).promise()
    )
    .then(() => callback(null, {
      statusCode: '301',
      headers: {'location': `${URL}/${key}`},
      body: '',
    })
)

只需使用一个临时变量:

.then(data => {
  let s = Sharp(data.Body);
  if(useCrop){
    s = s.crop(width, height)
  }
  if(useResize){
    s = s.resize(width, height)
  }
  return s.toFormat(setFormat)
  .withoutEnlargement(p_withoutEnlargement)
  .quality(quality)
  .max(max)
  .flatten()
  .toBuffer();
})

你也可以不做突变:

const orig = Sharp(data.Body);
const withPossibleCrop = useCrop ? orig.crop(width, height) : orig;
const withPossibleCropAndResize = useResize ? withPossibleCrop.resize(width, height) : withPossibleCrop;
return withPossibleCropAndResize.toFormat(…).…;