idea 提取接口重构_将提取重构为异步/等待

idea 提取接口重构

将提取重构为异步/等待 (Refactoring Fetch to Async/Await)

Photo by Dave Francis on Unsplash
戴夫·弗朗西斯 ( Dave Francis)Unsplash拍摄

Async/await is one of the most revolutionary features that have been added to JavaScript in the past few years. It offers an intuitive replacement to the syntactical mess that promises sometimes tend to be.

一个同步/ AWAIT是已经添加到最具革命性的功能之一JavaScript在过去的几年里。 它提供了对语法混乱的一种直观的替代,而这种混乱有时可能会发生。

There is nothing wrong with the good old Fetch API, which is made available by default to make ajax requests and:

良好的旧Fetch API没什么问题,默认情况下,该API可用于发出ajax请求,并且:

(…)provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

(…)提供了一个JavaScript接口,用于访问和操作HTTP管道的各个部分,例如请求和响应。 它还提供了全局fetch()方法,该方法提供了一种简单,逻辑的方式来跨网络异步获取资源。

A basic fetch request is really simple to set up. Tale a look at the following code:

基本的提取请求真的很容易设置。 看看下面的代码:

const apiUrl = "http://rallycoding.herokuapp.com/api/music_albums"fetch(apiUrl) // fetch data from API
.then(response => response.json()) // parse to JSON format
.then(data => console.log(data)) // do something with it
.catch(error => console.error(error)) // optional error handling
})

异步/等待101 (Async/Await 101)

Async/await is a relatively new (part of the so-called ECMAScript 2017 JavaScript edition) way to write asynchronous code. Previous alternatives for asynchronous code are callbacks and promises. Async/await is actually just syntactic sugar built on top of promises, and it makes asynchronous code look and behave a little more like synchronous code. Some argue it makes spotting asynchronous code more difficult and might require some getting used to.

Async / await是一种相对较新的(称为ECMAScript 2017 JavaScript版本的一部分)编写异步代码的方式。 异步代码的先前替代方法是回调和Promise。 异步/等待实际上只是建立在promise之上的语法糖,它使异步代码的外观和行为更像同步代码。 有人认为,这使得发现异步代码更加困难,并且可能需要一些习惯。

It is important to note that theawait keyword cannot be used outside the async function.

这是需要注意的重要的await关键字不能在外部使用async功能。

接受异步/等待的原因 (Reasons to embrace async/await)

  • It makes code concise and clean

    它使代码简洁明了
  • It allows us to avoid nesting our code

    它使我们避免嵌套代码
  • Makes it possible to handle both synchronous and asynchronous errors with try/catch

    使用try / catch可以处理同步和异步错误
  • Much easier to debug (I’m sure I don’t have to tell you to try to figure out where to drop a debugger inside a fetch function)

    调试起来容易得多(我确定我不必告诉您尝试找出将调试器放在提取函数中的位置)

只需三个简单的步骤即可将抓取转换为异步/等待 (Transform a fetch into async/await in three easy steps)

Here is the function we will be transforming for this example:

这是我们将为该示例转换的函数:

const apiUrl = "http://rallycoding.herokuapp.com/api/music_albums"function fetchAlbums() {
fetch(apiUrl)
.then(response => response.json())
.then(data => console.log(data))
})
}
  1. Identify the asynchronous function and put asyncbefore it:

    识别异步函数并将 async 放在 它前面:

async function fetchAlbums() {
...
}

2. Identify all the different promises in the function and add await in front of each of these promises, assign them to variables

2.确定函数中所有不同的promise,并在每个promise的前面添加await,将它们分配给变量

const res = await fetch(apiUrl)
const json = await res.json()

3. refactor the rest to make it look synchronous

3.重构其余部分以使其看起来同步

async function fetchAlbums() {
const response = await fetch(apiUrl)
const json = await response.json()
console.log(json)
}

Using async/await is not reserved for function using the function keyword and we can also use it as an arrow function, although the syntax is slightly different:

使用async / await并不保留给使用function关键字的函数使用,我们也可以将其用作箭头函数,尽管语法略有不同:

const fetchAlbums = async () => {
const response = await fetch(apiUrl)
const json = response.json()
console.log(json)
}

it can also be an anonymous function as in the following example where our asynchronous function is one of the arguments passed on to our passport.use function in our Google auth configuration. Here it is used with fetch:

它也可以是一个匿名函数,如以下示例所示,其中我们的异步函数是传递给我们Google auth配置中password.use函数的参数之一。 在这里它与提取一起使用:

passport.use(
new GoogleStrategy(credentials, (profile, done) => {
User.findOne({ googleId: profile.id }) // returns a promise
.then((existingUser) => {
if (existingUser) {
done(null, existingUser
} else {
new User({googleId: profile.id}).save()
.then(user => done(null, user))
}
})
})
)

after refactoring with async/await

用异步/等待重构后

passport.use(new GoogleStrategy(
credentials, async (profile, done) => {
const existingUser = await User.findOne({ googleId: profile.id })
if (existingUser) {
done(null, existingUser)
} else {
const user = await new User({googleId: profile.id}).save()
done(null, user)
}
})
)

翻译自: https://medium.com/@justynakuchta/promises-with-async-await-605645a6c0e8

idea 提取接口重构

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值