将async / await应用于提取然后调用

时间:2019-03-07 11:55:57

标签: javascript asynchronous async-await dropzone.js

我有以下代码,它们从imagesList中的图像URL数组读取,然后从这些图像中获取并将它们添加到myDropzone1框中。问题在于,我认为添加图像的顺序是提取完成的顺序,而不是数组中列出的顺序。

我可以想到的一种可能的解决方案是使用async / await,但是我不确定如何将其应用于这段代码。请帮忙。

for (var i = 0; i < imagesList.length; i++) {
   let name = imagesList[i];
   name = name.substring(name.lastIndexOf('/') + 1);

   fetch(imagesList[i])
       .then(res => res.blob())
       .then(blob => {
       let file = new File([blob], name, blob);
       myDropzone1.addFile(file);
   });
}

谢谢。

2 个答案:

答案 0 :(得分:0)

您做得对,您真的不需要async/await来解决此问题。您只需要确保您没有发起下一个呼叫,除非您没有上一个呼叫的响应。

您可以通过递归调用来实现,例如:

function fetchRecursively(imagesList, myDropzone1) {
  // execute only if there imageList has some value,
  if (imagesList.length) {
    let name = imagesList[0];
    name = name.substring(name.lastIndexOf('/') + 1);
    fetch(imagesList[0])
      .then(res => res.blob())
      .then(blob => {
        let file = new File([blob], name, blob);
        myDropzone1.addFile(file);

        // after a call has completed, shift the array and make next call.
        imagesList.shift();
        fetchRecursively(imagesList, myDropzone1);
     });
  }
  return;
}

或者,您可以使用Promise.all等待所有提取调用完成,然后[顺序]执行代码。

答案 1 :(得分:0)

我想你可以这样做:

const fetchImages = async () => {
    for (let i = 0; i < imagesList.length; i++) {
        let name = imagesList[i];
        name = name.substring(name.lastIndexOf('/') + 1);

        let res = await fetch(imagesList[i]),
            blob = res.blob(),
            file = new File([blob], name, blob);

        myDropzone1.addFile(file);
    }
}

fetchImages();