Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 返回前等待请求的响应_Javascript_Electron - Fatal编程技术网

Javascript 返回前等待请求的响应

Javascript 返回前等待请求的响应,javascript,electron,Javascript,Electron,我试图创建一个带有GET请求的函数,该函数返回GET请求中的一部分数据。然而,它在检索数据之前一直返回,所以我一直得到“未定义”。我如何设置它,使其在返回之前真正等待数据设置 let getInfo = async () => { const request = net.request({ url: URL }) return new Promise((resolve, reject) => { // Promise being here DOES work

我试图创建一个带有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)
})
编辑:这是仍不起作用的更新版本。我正在尝试使用,我不明白为什么这不起作用。“从那时起:”部分正确显示信息。但当从“外部”运行时:“打印未定义。该问题是否与
响应有关。on
嵌套在
请求中。on

解决方案:正如@NidhinDavid在他的回答中所显示的,问题是承诺在
的“响应”中。将
'GET'
请求从开始移动到结束,在Promise中修复它,以提供正确的输出。我已经更新了代码,以反映未来个人的需求。

让getInfo=()=>{
发布信息;
const request=net.request({
url:url
})
返回新承诺((解决、拒绝)=>{
请求.on('response',(response)=>{
response.on('data',(chunk)=>{
请求。写入(“”)
请求结束()
let body=JSON.parse(块)
info=body.data
如果(信息){
解析(信息)
}否则{
拒绝(“出了差错”);
}
});
});
})
}
getInfo()
。然后(数据=>{
//这将是您的信息对象
console.log(数据)
})
.catch(错误=>{
//如果出现任何错误,这将记录“出错”
console.log(错误)
})
让getInfo=()=>{
发布信息;
const request=net.request({
url:url
})
返回新承诺((解决、拒绝)=>{
请求.on('response',(response)=>{
response.on('data',(chunk)=>{
请求。写入(“”)
请求结束()
let body=JSON.parse(块)
info=body.data
如果(信息){
解析(信息)
}否则{
拒绝(“出了差错”);
}
});
});
})
}
getInfo()
。然后(数据=>{
//这将是您的信息对象
console.log(数据)
})
.catch(错误=>{
//如果出现任何错误,这将记录“出错”
console.log(错误)

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

异步函数总是返回一个承诺,所以要么使用该承诺,要么在内部等待数据并将其分配给某个变量。
通过将信息记录到控制台来检查信息中所需的有效数据。

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);

异步函数总是返回一个承诺,所以要么使用该承诺,要么在内部等待数据并将其分配给某个变量。
通过将信息记录到控制台,检查信息中所需的有效数据。

我找不到
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)
})

我找不到
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)
})


这是最基本的,谷歌会给你答案。至于初学者,请尝试使用
console.log(wait getInfo())
您能给出从何处导入网络的参考信息吗?@NidhinDavid我在谷歌上搜索了好几次,查看了几十页,并尝试了许多不同的方法。“你的建议是我尝试的第一件事,但它不起作用。”巴祖格尔我添加了一个答案来帮助你摆脱混乱。希望有帮助!不要更新你的问题以不再有问题,这就是答案部分的目的。现在问题不重要了。这是基础,谷歌会给你答案的。至于初学者,请尝试使用
console.log(wait getInfo())
您能给出从何处导入网络的参考信息吗?@NidhinDavid我在谷歌上搜索了好几次,查看了几十页,并尝试了许多不同的方法。“你的建议是我尝试的第一件事,但它不起作用。”巴祖格尔我添加了一个答案来帮助你摆脱混乱。希望有帮助!不要更新你的问题以不再有问题,这就是答案部分的目的。现在问题不重要了,我也试过了。它还打印了“undefined”(未定义)stillDo检查
数据
是否是
主体
对象上的有效键。此外,您是否可以共享更多代码,以便我可以在本地对其进行测试,您可能需要返回承诺,并且一切都会很好地为您服务。不使用fetch的具体原因是什么?如果我从响应侦听器内部输入
console.log(info)
,然后立即返回
return info
,它将正常打印,但日志将显示
undefined
,然后显示
{correct info}
。我无法将
request.write
request.end
放入侦听器中,因为它永远不会被触发。我没有特别的理由使用这种方法,只是我正在构建一个电子应用程序,并考虑使用电子原生方法。好了,给我一分钟,我会更新答案,然后尝试我也尝试过。它还打印了“undefined”(未定义)stillDo检查
数据
是否是
主体
对象上的有效键。此外,您是否可以共享更多代码,以便我可以在本地对其进行测试,您可能需要返回承诺,并且一切都会很好地为您服务。不使用fetch的具体原因是什么?如果我从响应侦听器内部输入
console.log(info)
,然后立即返回
return info
,它将正常打印,但日志将显示
undefined
,然后显示