【问题标题】:How to call API inside a Promise Javascript/React如何在 Promise Javascript/React 中调用 API
【发布时间】:2022-01-06 17:30:59
【问题描述】:

目标:在设置状态路径之前,我需要从cloudinary 获取image_url。所以我创建了一个 Promise 并尝试执行以下操作:

export const uploadToCloudinary = (imageData, setImageURL) => {
  if (imageData) {
    const data = new FormData();
    data.append('file', imageData);
    fetch(CLOUDINARY_BASE_URL, {
      method: 'POST',
      body: data,
    })
      .then(response => response.json())
      .then(responseData => {
        console.log('api: ', responseData.secure_url);
        setImageURL(responseData.secure_url);
      })
      .catch(error => {
        console.log(`[ERROR] While trying to upload: ${error.message}`);
        setImageURL(null);
      });
  } else {
    setImageURL(null);
  }
};

component.js

const [imageURL, setImageURL] = useState(null);

const sendMessage = () => {
    Keyboard.dismiss();
    if (input || image) {
      uploadToCloudinary(image, setImageURL)
      console.log(imageURL); // THIS PRINTS FIRST & obviously it is null.
      const message = {
        ...someData,
        image: imageURL, // hence image: null,
      };
      setImageURL(null);
    }
  };

控制台输出:

LOG null
LOG api: https://res.cloudinary.com/abcd/image/upload/v12324/luxjoasdceavl8asdc2dxb.jpg

如果我选择一个图像,那么在承诺得到解决之后,那么只有它应该setImageURL 对吗? (因此破坏了整个目的)。我在这里做错了什么?

【问题讨论】:

  • 我认为包装 fetch 的承诺是不必要的。你也白白兑现了承诺?
  • fetch 已经返回了一个承诺。你包裹它的那个永远不会拒绝,因为那个方法永远不会被调用,并且在内部承诺完成之前解析。
  • @evolutionxbox 因为我需要在获取 fetch api 的结果后设置 imageURL 的状态。
  • @jonrsharpe 我的目标是 -> 如果我在消息中提供图像,那么它应该调用 uploadToCloudinary 函数 & 只有在获取数据后,setState of imageURL,否则如果我只提供text & not image,那么它不应该调用 API,这就是为什么我要创建额外的 Promise 来处理这种情况。
  • 但无论如何,你是在 inner 承诺中这样做的,在 .then/.catch 中。

标签: javascript reactjs react-native


【解决方案1】:

你不等待uploadToCloudinary(image, setImageURL),所以它下面的console.log是空的。

我会做这样的事情:

  const [imageURL, setImageURL] = useState(null);
  const [message, setMessage] = useState('');

  useEffect(() => {
    if (imageURL) {
      setMessage({
      ...someData,
      image: imageURL, // hence image: null,
    });
    setImageURL(null);
  }
  }, [imageURL]);

  const sendMessage = () => {
      Keyboard.dismiss();
      if (input || image) {
        uploadToCloudinary(image, setImageURL);        
      }
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-13
    • 2021-10-09
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 2023-03-27
    • 2023-03-11
    相关资源
    最近更新 更多