哪个是更好的js编码实践?

时间:2017-11-13 23:55:42

标签: javascript

我需要发送api调用以从多个源获取数据。我得到的数据采用不同的格式(数组,对象,嵌套数组)。我感觉很好的一件事就是有一个功能可以为我提取我需要的部件。

现在我想知道我是否应该使用这个提取功能,或者只是在我使用它时提取我需要的数据。(简单地说:哪一个是更好的做法?)

我个人更喜欢后者,因为我不需要来回确定我需要提取哪部分数据。 例如

内联提取

const  data = get("example.com").data[0].Users;

使用函数提取数据

const data = getData("example.com";

const getData = async(url)=>{
   const rawData= await get(url);
   switch(url){
    case EXAMPLE_URL:
      return rawData.data[0].Users;
    case OTHER_EXAMPLE_URL:
      return rawData.data;
    case  OTHER_URL:
     return rawData.data[0].Enum;

}
}

2 个答案:

答案 0 :(得分:1)

我将它分成多个功能。 Imo,调用者不应该知道要传递什么url来获得一些不同的值。

你不知道你是否最终会从同一个网址中获取两个不同的值。

//maybe using a simple utility
const getUrlPath = (url, ...path) => {
  let fetchPath = path.reduceRight((next, key) => obj => next(obj[key]), identity);
  return () => get(url).then(fetchPath);
}
const identity = v => v;    

//and then creating the different functions to get the different values
const getExample = getUrlPath(EXAMPLE_URL, "data", 0, "Users");
const getOther = getUrlPath(OTHER_EXAMPLE_URL, "data");
...

答案 1 :(得分:1)

你应该瞄准的一个核心理念是一个函数应该只做一件事,但要非常擅长,所以不要以“一个函数来统治它们”为目标。溶液

在你的情况下,你在两个任务中寻找三件事,从url获取,并从结果中提取数据。我建议你为那些

创建功能
// Task 1: Fetch URL
const fetchUrl = async () => {
  const response = await fetch('example.com', { ...some options });

  // Do some error checking (just demo code for idea)
  if (response.status === 'error') throw new Error('fethcing Error Message');

  // If no error found, return with response
  return response;
}


// Task 2: extract data
const getUserFromResponse = response => response.data[0].Users;

const getEnumFromResponse = response => response.data[0].Enum;

现在你可以将它们组合成你的工作职能了。

const getUser = async () => {
  try {
    const response = await fetchUrl();
    const user = getUserFromResponse(response);
    return user;
  } catch (e) {
     // do error handling
  }
}

const getEnum = async () => {
  try {
    const response = await fetchUrl();
    const enum = getEnumFromResponse(response);
    return enum;
  } catch (e) {
     // do error handling
  }
}

将功能分解为单个任务将使创建测试用例变得更加容易并迫使您编写更多可重复使用的代码,希望这会有所帮助,欢呼:)