并行,当 await 请求两个 api 时,会等第一个返回结果之后第二个才会执行:

    1. const fetch = require("node-fetch")
    2. async function getZhihuColumn(id) {
    3. const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
    4. const response = await fetch(url)
    5. return await response.json()
    6. }
    7. const showCloumnInfo = async () => {
    8. const feweekly = await getZhihuColumn("feweekly")
    9. const toolingtips = await getZhihuColumn("toolingtips")
    10. console.log(`标题:${feweekly.title}`)
    11. console.log(`简介:${feweekly.intro}`)
    12. console.log(`标题:${toolingtips.title}`)
    13. console.log(`简介:${toolingtips.intro}`)
    14. };
    15. showCloumnInfo()

    串行,先调用异步操作,之后通过 await 输出结果

    1. const fetch = require("node-fetch")
    2. const sleep = (timeout) => new Promise((resolve, reject) => {
    3. setTimeout(resolve, timeout);
    4. })
    5. async function getZhihuColumn(id) {
    6. await sleep(2000)
    7. const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
    8. const response = await fetch(url)
    9. return await response.json()
    10. }
    11. const showCloumnInfo = async () => {
    12. console.time('showColumnInfo')
    13. const feweeklyPromise = getZhihuColumn("feweekly")
    14. const toolingtipsPromise = getZhihuColumn("toolingtips")
    15. const feweekly = await feweeklyPromise
    16. const toolingtips = await toolingtipsPromise
    17. console.log(`标题:${feweekly.title}`)
    18. console.log(`简介:${feweekly.intro}`)
    19. console.log(`标题:${toolingtips.title}`)
    20. console.log(`简介:${toolingtips.intro}`)
    21. console.timeEnd('showColumnInfo')
    22. };
    23. showCloumnInfo()