gpt4 book ai didi

node.js - 异步/等待 Node.js https.get

转载 作者:行者123 更新时间:2023-12-03 18:32:03 25 4
gpt4 key购买 nike

我正在尝试使用 async/await 简化代码
但是制作有问题https.get带有 async/await 结构。
我知道如何使用第三方模块执行此操作,但更喜欢 native node.js https模块。
下面的代码对我不起作用:

async function get_page() {

const https = require('https')
const url = 'https://example.com'

const util = require('util')
const https_get = util.promisify(https.get)

const data = await https_get(url)

do_awesome_things_with_data(data)
}
此代码工作正常:
function get_page() {

const https = require('https')
const url = 'https://example.com'

let data = ''

https.get(url, res => {

res.on('data', chunk => { data += chunk })

res.on('end', () => {

do_awesome_things_with_data(data)

})
})
}

最佳答案

https.get不返回可能是 promisified 的内容因为回调的签名不匹配 (err, value) ,所以你不能await它。
但是,您可以包装 https.get在 Promise 中调用,像这样,然后在调用 get_page 时等待

const https = require('https')

async function get_page() {
const url = 'https://example.com'

return new Promise((resolve) => {
https.get(url, res => {

res.on('data', chunk => { data += chunk })

res.on('end', () => {

resolve(do_awesome_things_with_data(data));

})
})
})
}

// usage

(async () => await get_page())()
编辑
我已更新我的答案以包含 https.get 的注释无法 promise 和移动 require('https')在函数调用之外。

关于node.js - 异步/等待 Node.js https.get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65306617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com