简体   繁体   English

从 Async/Await Function 返回一些东西有什么意义?

[英]What's the point of returning something from an Async/Await Function?

I've created a code snippet here that fetches data about a certain country using REST Countries API.我在这里创建了一个代码片段,它使用 REST 国家/地区 API 获取有关某个国家/地区的数据。 The function works fine, and returns a pending promise. function 工作正常,并返回待处理的 promise。 That promise's fulfilled value will equal an object containing key value pairs for the country's capital, name, and code.该承诺的履行值将等于 object 包含国家首都、名称和代码的键值对。

But if I wanted to use them for something, why wouldn't I just set that very same object equal to a variable and continue to program new actions inside my async function?但是,如果我想将它们用于某事,我为什么不将相同的 object 设置为等于一个变量并继续在我的异步 function 中编写新操作? Why bother trying to use values gained asynchronously on the global scope?为什么还要尝试使用在全局 scope 上异步获得的值?

function getJSON(url, errorMSG = 'Something went wrong') {
  // feed it the fetch URL, then your customized error message
  return fetch(url).then(response => {
    if (!response.ok) throw new Error(errorMSG);
    return response.json();
  });
}

async function countryData(nation) {
  try {
    const info = await getJSON(
      `https://restcountries.eu/rest/v2/name/${nation}?fullText=true`,
      'Invalid country selected'
    );
    return {
      // Fullfilled value of promise
      capital: info[0].capital,
      name: info[0].name,
      code: info[0].cioc,
    };
  } catch (err) {
    console.error(err); // display your custom error message
  }
}
console.log(countryData('Canada'));

fetch is an async function. fetch是一个异步 function。 Why do they resolve the promise to a response object, instead of continuing to run extra actions once they have it?为什么他们将 promise 解析为响应 object,而不是在获得后继续运行额外操作? Because they don't know what you want to do with it.因为他们不知道你想用它做什么。 It would be impossible for fetch to handle every possible thing that should happen next, so it just has a single job: get the data, then return it (in a promise). fetch 不可能处理接下来应该发生的所有可能的事情,所以它只有一个工作:获取数据,然后返回它(在一个承诺中)。 You can then combine this with whatever other code you like.然后,您可以将其与您喜欢的任何其他代码结合使用。

On a smaller scale, this may happen with countryData too.在较小的范围内, countryData也可能发生这种情况。 You might have 10 different parts of your app that want to do things with the result from countryData .您的应用程序中可能有 10 个不同的部分想要处理countryData的结果。 It may not be "impossible" for countryData to implement all 10 things, but it's definitely impractical and not a good idea. countryData实现所有 10 件事可能并非“不可能”,但这绝对是不切实际的,也不是一个好主意。 Instead, countryData can be written to have one job: get the country data and return it.相反, countryData可以写成一项工作:获取国家数据并返回。 Then each of the 10 pieces of code can do their own things with the result.然后这 10 段代码中的每一个都可以对结果做自己的事情。

This isn't about it being async, the same principles apply to synchronous code to.这不是关于它是异步的,相同的原则适用于同步代码。 If you can keep code focused on a single task, without entangling it with the needs of other pieces of code, then your code becomes easier to maintain.如果您可以将代码集中在单个任务上,而无需将其与其他代码段的需求纠缠在一起,那么您的代码将变得更易于维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM