nodeschool / discussions

:school::speech_balloon: need help with nodeschool? or just wanna ask a question? open an issue on this repo!
489 stars 107 forks source link

玩转异步 #2910

Open lws-xzx opened 1 year ago

lws-xzx commented 1 year ago

Notes

Please delete this section after reading it

If you have a problem with an error message:

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 commented 1 year ago

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