discussions icon indicating copy to clipboard operation
discussions copied to clipboard

玩转异步

Open lws-xzx opened this issue 1 year ago • 1 comments

Notes

  • If you have a question about the NodeSchool organization: Please open an issue in nodeschool/organizers
  • If you want to improve or contribute to workshoppers: Please open an issue in workshopper/org
  • Did you see the guide for questions? https://github.com/nodeschool/discussions#when-you-have-a-problem

Please delete this section after reading it

If you have a problem with an error message:

  • node version: <run "node -v" in you terminal and replace this>
  • npm version: <run "npm -v" in you terminal and replace this>
  • os: windows 7/windows 10/mac/linux

Error output

D:\System\theca\A-Super\Sep\asyncTest.js:28
})()
  ^

TypeError: (intermediate value)(...) is not a function
    at Object.<anonymous> (D:\System\theca\A-Super\Sep\asyncTest.js:28:3)
    at Module._compile (node:internal/modules/cjs/loader:1233:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1287:10)
    at Module.load (node:internal/modules/cjs/loader:1091:32)
    at Module._load (node:internal/modules/cjs/loader:938:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
    at node:internal/main/run_main_module:23:47

Node.js v20.5.1

My Code

js
const http = require("http");

let dataArray = []

const getResponse = function (url) {
   return new Promise(function (resolve) {
       http.get(url, function (response) {
           let data = ""
           response.on("data", function (chunk) {
               data += chunk
           })
           response.on("end", () => {
               resolve(data)
           })
       })
   })
}

(async function() {
    for (let i = 2; i < process.argv.length; i++) {
        let data = await getResponse(process.argv[i])
        dataArray.push(data)
    }

    dataArray.forEach(data => {
        console.log(data)
    })
})()

lws-xzx avatar Sep 10 '23 07:09 lws-xzx

`const http = require("http");

let getResponse = async (url) => { let response = await http.get(url, function (res) { let data = "" res.setEncoding("utf8") res.on("data", function (chunk) { data += chunk }) res.on("end", function () { console.log(data) }) }) }

let urls = process.argv.slice(2)

for (let url of urls) { getResponse(url) }`

lws-xzx avatar Sep 10 '23 08:09 lws-xzx