尽管API调用成功,但仍未返回结果-Typescript

时间:2020-08-26 06:55:14

标签: typescript async-await

 if (imageFile !== undefined) {
  s3Url = await uploadImage(imageFile, user.user_id);
}

 const uploadImage = async (attachment: IAttachment, userId: string) => {
  if (!attachment) {
    return '';
  }

  // attempting to upload image to S3
  try {
    await upload({
      file: attachment.file,
      fileName: attachment.fileName,
      userId,
    })
      .then((s3Url) => {
        return s3Url;
      })
      .catch((e) => {
        return Promise.reject(e);
      });
  } catch (e) {
    return Promise.reject(e);
  }
};

唤醒结果,如下所示:

enter image description here

无论何时返回结果

enter image description here

响应:

enter image description here

1 个答案:

答案 0 :(得分:1)

这是因为uploadImage未返回任何内容:

// Promise is handled but not returned.
await upload({
    file: attachment.file,
    fileName: attachment.fileName,
    userId,
  })
    .then((s3Url) => {
      // This value is lost.
      return s3Url;
    })
    .catch((e) => {
      return Promise.reject(e);
    });

首先,我将重构uploadImage以仅使用async/await

const uploadImage = async (attachment: IAttachment, userId: string) => {
  if (!attachment) {
    return '';
  }

  // I removed try/catch block because the error was rethrown without modification.
  const s3Url = await upload({
    file: attachment.file,
    fileName: attachment.fileName,
    userId,
  })
   
  return s3Url;
};

现在您看到返回了一个值,并且您不再应该获得unedfined