我正在尝试使用 GET 请求创建一个函数,该函数从 GET 请求返回部分数据。但是,它在检索数据之前不断返回,因此我不断收到“未定义”。我如何设置它以便它实际上在返回之前等待数据设置?
let getInfo = async () => {
const request = net.request({
url: URL
})
return new Promise((resolve, reject) => { // Promise being here DOES work
request.on('response', (response) => {
response.on('data', (chunk) => {
//return new Promise((resolve, reject) => { //Promise being here does NOT work
let body = JSON.parse(chunk)
let info = body.data
if (info){
resolve(info);
}
reject();
//})
});
});
request.write('')
request.end()
}).then(data => {
console.log("From then: "+data)
return data
})
}
getInfo().then(data => {
console.log("From outside: "+data)
})
编辑:这是仍然无法工作的更新版本。我正在尝试使用 native electron method,但我不明白为什么这不起作用。 “从那时起:”部分正确显示信息。但是当运行“从外面:”它打印未定义。该问题是否与嵌套在 response.on
中的 request.on
有任何关系?
解决方案:正如@NidhinDavid 在他的回答中所表明的,问题是承诺在 'response'
侦听器中。在 Promise 内从头到尾移动 'GET'
请求将其修复为提供正确的输出。我已经更新了我的代码,以反映未来的个人。
答案 0 :(得分:2)
let getInfo = () => {
let info;
const request = net.request({
url: URL
})
return new Promise((resolve, reject) => {
request.on('response', (response) => {
response.on('data', (chunk) => {
request.write('')
request.end()
let body = JSON.parse(chunk)
info = body.data
if (info) {
resolve(info)
} else {
reject('Something went wrong');
}
});
});
})
}
getInfo()
.then(data => {
// this will be your info object
console.log(data)
})
.catch(err => {
// this will log 'Something went wrong' in case of any error
console.log(err)
})
您需要在 on
类型的事件处理程序中返回。详细了解异步代码和同步代码 here
答案 1 :(得分:1)
我找不到 net
模块,Nodejs 中包含的模块没有请求方法。因此,为了获得事件发射器的类似概念并承诺我使用 http
模块并执行 http 请求来获取 json 并解析它
'use strict'
var https = require('https');
const getInfo = async () => {
// create a new promise chain
// remember it is a chain, if one return is omitted
// then the chain is broken
return new Promise((resolve, reject) => {
var options = {
host: 'support.oneskyapp.com',
path: '/hc/en-us/article_attachments/202761727/example_2.json'
};
// start the request
https.request(options, function (response) {
var str = '';
// data arrives in chunks
// chunks needs to be stitched together before parsing
response.on('data', function (chunk) {
str += chunk;
});
// response body obtained
// resolve (aka return) the result
// or parse it, or do whatever you want with it
response.on('end', function () {
resolve(str)
});
// errors are another event
// listen for errors and reject when they are encountered
response.on('error', function (err) {
reject(err)
})
}).end()
})
}
//*********************************************
// using async await
//*********************************************
// if this is the entry point into app
// then top-level async approach required
(async ()=>{
try{
let data = await getInfo()
console.log("From ASYNC AWAIT ")
console.log(JSON.stringify(JSON.parse(data)))
}
catch (err) {
console.log("operation failed, error: ", err)
}
})();
//************************************************
// using promise chains
//************************************************
getInfo()
.then((data)=>{
console.log("FROM PROMISE CHAIN ")
console.log(JSON.stringify(JSON.parse(data)))
})
.catch((err)=>{
console.log("operation failed, error: ", err)
})
答案 2 :(得分:0)
Tyr 这个,它可能对你有用,
let info;
const getInfo = async (_url)=>{
const response = await fetch(_url);
const data = await response.json();
info = data;
} ;
const url = "some url";
getInfo(url);
console.log(info);
异步函数总是返回一个promise,因此要么使用该promise,要么在内部等待数据并将其分配给某个变量。 通过将信息记录到控制台来检查信息中所需的有效数据。