异步等待未按预期工作

Async await is not working as expected to work

我试图在将图像上传到云端后对其进行设置,但我似乎遗漏了一些东西。 输出不符合预期。

我希望输出包含所有图像。 但它只是 0。

 useEffect(() => {
    console.log("============ From UseEffect ==========")
    console.log("Images now Contain : ", images);
  }, [images]);

const uploadFilesToCloud = async () => {
    const data = new FormData();
    for (let i = 0; i < imageUrls.length; i++) {
      const finalImage = await getBase64FromUrl(imageUrls[i]);
      data.append("file", finalImage);
      data.append("upload_preset", "myPreset");
      const res = await fetch(
        "https://api.cloudinary.com/v1_1/dpurb6xes/image/upload",
        {
          method: "Post",
          body: data,
        }
      );
      const response = await res.json();
      setImages((old) => [...old, response.secure_url]);
    }
  };

const onClick = async (e) => {
await uploadFilesToCloud();
const myForm = {
  name: name,
  imageUrls: images,
};
  console.log("form data is ", myForm);
}

令人惊讶的输出是:

我现在的实际问题是。

  1. 虽然图像在设置 myForm.imgUrls = 图像之前有一个元素。 即使那样 myForm.imageUrls 也没有元素。怎么样?
  2. 我想要的是,在设置好接收到的图像之后,才应该用图像初始化表单。

你能说说怎么做吗?

我认为这里实际上不需要状态。将 imageUrls 数组映射到 fetch Promise 和 return Promise.all 来自 upload 的数组。 onClick 处理程序可以 await Promise 数组来解析和使用已解析图像 URL 数组。

示例:

const App = () => {
  const upload = () => {
    const imgURLs = imageUrls.map(data => {
      return fetch(
        "https://api.cloudinary.com/v1_1/dpurb6xes/image/upload",
        {
          method: "Post",
          body: data,
        }
      ).then(response => response.json())
      .then(response => response.secure_url);
    });

    return Promise.all(imgURLs);
  };

  const onClick = async () => {
    const imageURLs = await upload();
    const myForm = {
      formImages: imageURLs,
    };
    console.log("Form details", myForm);
  };

  return (
    <>
      <div className="container">
        <button
          type="button"
          onClick={onClick}
        >
          Click me
        </button>
      </div>
    </>
  );
};

如果您需要将图像 URL 存储在 state 中,一旦一切都解决了,就在 onClick 处理程序中执行此操作。

示例:

const onClick = async () => {
  const imageURLs = await upload();
  const myForm = {
    formImages: imageURLs,
  };
  console.log("Form details", myForm);
  setimages(imageURLs);
};