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)
}
})()