如何执行两个回调功能



我正在使用带有react/axios的云API,并且想知道我如何在Axios调用之前和之后都能拉数据。我的问题是,如果我使用一个回调,我只能将一个或另一个数据放置。因此,可以使用两个回调,如果是这样,您将如何做?

或我应该以不同的方式解决这个问题?

我想要的是将上传的进程提出,并能够将该值存储到状态。我唯一的问题是我不确定正确的方法吗?我需要在onUploadProgress Fucntion内部进行。

这是代码:

组件中的功能:

uploadImage(files) {
    const image = files[0];
    const cloudName = 'hyszj0vmt';
    const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;
    const apiSecret = '***********';
    const uploadPreset = '**************';
    const timestamp = Date.now() / 1000;
    const paramStr = `timestamp=${timestamp}&upload_preset=${uploadPreset}${apiSecret}`;
    const signature = sha1(paramStr);
    const params = {
      api_key: '*******',
      timestamp: timestamp,
      upload_preset: uploadPreset,
      signature: signature
    };
    APIManager.upload(url, image, params, (err, response) => {
      if (err) {
        console.log(`UPLOAD ERROR: ${err}`);
        return;
      }
      const imageUrl = response['secure_url'];
      let updatedProfile = Object.assign({}, this.state.updated);
      updatedProfile['image'] = imageUrl;
      this.setState({
        updated: updatedProfile
      });
    });
  }

apimanager函数:

upload: (endpoint, file, params, callback) => {
    let fd = new FormData();
    fd.append('file', file);
    Object.keys(params).forEach(key => {
      fd.append(key, params[key]);
    });
    const config = {
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
      onUploadProgress: progressEvent => {
        const progress = Math.round(
          progressEvent.loaded * 100.0 / progressEvent.total
        );
        console.log(progress + '%');
      }
    };
    axios
      .post(endpoint, fd, config)
      .then(response => {
        const { data } = response;
        callback(null, data);
      })
      .catch(err => {
        callback(err, null);
      });
  }
};

怎么样?

upload: (endpoint, file, params, callback, callbackProgress) => {
    ...
    const config = {
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
      onUploadProgress: progressEvent => {
        const progress = Math.round(
          progressEvent.loaded * 100.0 / progressEvent.total
        );
        callbackProgress(progress);
      }
    };
    ...
});

用法:

APIManager.upload(url, image, params, (err, response) => {
  ...
}, (progress) => {
    console.log(progress);
});

相关内容

  • 没有找到相关文章

最新更新