导出Promise API调用以重复使用

时间:2018-10-12 05:34:05

标签: javascript reactjs promise es6-promise

我的问题是关于React应用程序无法识别的行为。我写了关于API调用的承诺,并将它们导出到一个文件中,因为许多组件都会使用它们。问题在于,这些导出的调用甚至在我加载应用程序之前就已执行。

//in commonAPI.js with other exports of similar promises
export var loadDesignationTypes = new Promise(function (resolve, reject) {

    axios.get('http://localhost:7002/commonAPI/getDesignations')
        .then(response => {
            if (response.data.success) {
                var designationObjAr = response.data.resultEmployeeDesignations;
                resolve(designationObjAr);
            }
        }).catch(function (error) {
            console.log("designation err " + error);
            reject(error)
        });
});

内部组件:

import { loadDesignationTypes, loadDepartmentTypes,
          loadLocationTypes, loadMaritialStatus } from '../../../CommonAPIs';

 //in a function
 const results = await Promise.all([loadDesignationTypes,
            loadDepartmentTypes,loadLocationTypes, loadMaritialStatus]);

更让我感到困惑的是,还执行了其他promise导出,这些导出未在与被称为promise驻留在同一文件中的组件内部进行调用。

1 个答案:

答案 0 :(得分:2)

当模块的代码运行时,模块当前正在同步运行new Promise(.. ,而解释器试图找出每个模块导入和导出的内容。如果您希望axios.get而不是自动运行,请导出一个函数,该函数在调用时创建一个Promise而不是一个普通的Promise

您还应该注意不要使用explicit Promise construction antipattern-只需返回Promise链即可:

export var loadDesignationTypes = () => axios.get('http://localhost:7002/commonAPI/getDesignations')
  .then(response => {
    if (response.data.success) {
      return response.data.resultEmployeeDesignations;
    }
    // if not successful, you probably want to throw an error:
    throw new Error('Not successful');
  }).catch(function (error) {
    // If this console.log statement isn't necessary,
    // better to leave the catch out entirely
    // and leave error handling to the consumer
    console.log("designation err " + error);
    throw error;
  });

然后,在使用模块中,将其与Promise.all一起使用时,调用调用函数:

const results = await Promise.all([
  loadDesignationTypes(),
  // etc