There’s a special syntax to work with promises in a more comfortable fashion, called “async/await”. It’s surprisingly easy to understand and use.
async/await是一种让开发者更舒服地写Promise的方式。
关于它的用法可以详见下面两篇文档:
下面我以一个网页爬虫代码为例,
代码1:这是传统的Promise写法, then/catch的写法。
后
// index.js
const axios = require('axios')
const myArgs = process.argv.slice(2)
const branch = myArgs[0]
const normalizeWar = warType => {
if(warType === "microstrategy") warType = "MicroStrategy"
return warType
}
const warType = normalizeWar(myArgs[1])
const URL = "https://XXX"
// The 1st request
axios.post(URL, {
action: 'coreui_Browse',
method: 'read',
data: [{
repositoryName: 'releases',
node: `com/microstrategy/${branch}/${warType}`
}],
type: 'rpc',
tid: 10
}).then((response) => {
// Get the URL of the branch
let wars = response.data.result.data;
wars = wars.filter(war => war.type === "component")
let war;
if(wars.length > 0) {
war = wars[wars.length - 1]
}
if(war === undefined) {
} else {
// The 2nd request
axios.post(URL, {
action: 'coreui_Browse',
method: 'read',
data: [{
repositoryName: "releases",
node: `com/microstrategy/${branch}/${warType}/${war.text}`
}],
type: "rpc",
tid: 20
}).then(response => {
let links = response.data.result.data
links = links.filter(link => link.text.match(/^\S+war$/))
if(links.length > 0){
const text = links[0].text
console.log(text)
}
})
}
})
代码2: 这是async/await的写法。相较于代码1写法,这种写法,没有回调
,没有链式
,是顺序
的范式。这种写法的好处是代码更加简洁明了,符合开发者的思维习惯,易于阅读。
// index.js
(async () => {
const axios = require('axios')
const myArgs = process.argv.slice(2)
const branch = myArgs[0]
const normalizeWar = warType => {
if(warType === "microstrategy") warType = "MicroStrategy"
return warType
}
const warType = normalizeWar(myArgs[1])
const URL = "https://XXX"
// The 1st post request
let response = await axios.post(URL, {
action: 'coreui_Browse',
method: 'read',
data: [{
repositoryName: 'releases',
node: `com/microstrategy/${branch}/${warType}`
}],
type: 'rpc',
tid: 10
})
let wars = response.data.result.data;
wars = wars.filter(war => war.type === "component")
let war;
if(wars.length > 0) {
war = wars[wars.length - 1]
}
if(war === undefined) {
return;
}
// The 2nd post request
response = await axios.post(URL, {
action: 'coreui_Browse',
method: 'read',
data: [{
repositoryName: "releases",
node: `com/microstrategy/${branch}/${warType}/${war.text}`
}],
type: "rpc",
tid: 20
})
let links = response.data.result.data
links = links.filter(link => link.text.match(/^\S+war$/))
if(links.length > 0){
const text = links[0].text
console.log(text)
}
})()