导出Promise API调用以重用

问题描述 投票:1回答:1

我的问题是关于反应应用程序的无法识别的行为。我为API调用编写了promises并将它们导出到一个文件中,因为许多组件都会使用它们。问题是那些导出的调用甚至在我在app load上调用之前就已执行了。

//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的同一文件中。

javascript reactjs promise es6-promise
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.