如何动态创建和链接获取api调用?

时间:2017-10-28 06:35:45

标签: javascript react-native fetch-api

在我的应用程序中,用户提交表单后,我可以访问一系列图像,我需要调用后端将所有上传的照片保存到我们的云服务器。

我们/上传api端点一次只能获取一张图片。如何为此阵列中的每个图像创建一个api调用,并将它们链接到一个接一个的链接?我以为我可以以某种方式使用reduce来做这件事,但我并不是百分之百确定如何去做。

以下是我为单张图片上传进行api调用的方式:

    const api = "https://appName.herokuapp.com/upload";
    const uri = photos[0];
    const formData = new FormData();

    formData.append('image', {
      uri,
      name: `photo.jpg`,
      type: `image/jpg`,
    });

    const options = {
      method: 'POST',
      body: formData,
      headers: {
        Authorization:`Basic ${base64.encode(BACKEND_AUTHENTICATION_HEADER)}`,
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data',
      },
    };

    fetch(api, options)
      .catch((e) => console.log(e))
      .then((response) => {
        console.log(response);
      })

2 个答案:

答案 0 :(得分:2)

使用Promise.All,您应该可以启动多个API调用并等待所有这些调用解析。 传递给then()的Promise.all函数接收一个包含结果的数组。 例如:

Promise.all([/*Array of promises*/]).then(function(results){
    //Results is an array
}).catch(function(error){
    //Handle errors
}

这里是一个jsFiddle:http://jsbin.com/yuqabizado/2/edit?html,js,output

编辑: - 删除了与Promise.all兼容性问题的评论。谢谢@zvona指出这一点。

答案 1 :(得分:0)

如果您正在使用redux,则可以执行以下操作:

  • 创建要上传的图像数组
  • 创建一个上传图像的操作,该图像将索引作为参数,并将为所有后续索引递归调用自身
  • 在索引0中调用您的操作传递时,操作可以递归上传该点的所有图像

这背后的逻辑:

imagesArray: [ image1, image2, image3 ]; // each image is an object

将您的行动称为:

store.dispatch(Actions.recursivelyUploadImages(0, imagesArray));
// If your action is defined outside of your current scope
// you can either bind it or pass in the imagesArray

然后你的行动将被定义为:

recursivelyUploadImages(index, array) {
  // construct/define your api/options here
  fetch(api, options)
      .catch((e) => console.log(e))
      .then((response) => {
        console.log(response);
        if (index < array.length - 1) {
          // call recursiveUploadImages(index+1, array);
        }
      })
}

如果这是一个很好的解决方案,我现在不知道,我对react和redux的了解非常有限,我只能根据我目前的经验考虑这种解决方案。

相关问题