我是否承诺使用以下代码?

时间:2017-06-02 04:19:16

标签: javascript promise

代码有效,但我想知道我是否过度承诺

我有这个Redux Action

import Promise from 'bluebird';
const uploadAsynch = Promise.promisify(api.upload);

uploadFiles : function(data, dispatch){
    var data = {
      ep:"EP_UPLOAD",
      payload: {
       files: data.files,
       profile: data.profile
      }
    }
    uploadAsynch(data).then((result)=>{
      dispatch({type: FILES_UPLOADED})
    });
  },

api.upload是以下

import axios from 'axios';

upload : function(data, callback){
    var files = new FormData();
    for(var i=0; i<data.payload.files.length; i++){
      files.append('files', data.payload.files[i], data.payload.files[i].name);
    }
    axios.post(apiEndpoints[data.ep], files, {
      headers: {
        'accept': 'application/json',
        'Accept-Language': 'en-US,en;q=0.8',
        'Content-Type': `multipart/form-data; boundary=--*`,
      }
    })
    .then((response) => {
      callback(null, response)
    }).catch((error) => {
      callback(error)
    });
  },

所以我想知道。如果Axios是基于承诺的请求客户端,那么在动作中用蓝鸟包装它是否正确?

1 个答案:

答案 0 :(得分:0)

我说你的承诺不足,因为你没有将承诺用于他们的全部能力。但是,你会回退到回调,同时再次宣传该功能,这是毫无意义的。只是return你最初的承诺。

// no promisification
uploadFiles: function(data, dispatch){
  var data = {
    ep:"EP_UPLOAD",
    payload: {
      files: data.files,
      profile: data.profile
    }
  }
  return api.upload(data).then(result =>
//^^^^^^
    dispatch({type: FILES_UPLOADED})
  );
}

import axios from 'axios';

upload: function(data) { // no callback
  var files = new FormData();
  for (var i=0; i<data.payload.files.length; i++){
    files.append('files', data.payload.files[i], data.payload.files[i].name);
  }
  return axios.post(apiEndpoints[data.ep], files, {
//^^^^^^
    headers: {
      'accept': 'application/json',
      'Accept-Language': 'en-US,en;q=0.8',
      'Content-Type': `multipart/form-data; boundary=--*`,
    }
  });
}