在返回之前等待请求的响应

Wait for response from request before returning

我正在尝试使用 GET 请求创建一个函数,该函数 returns 来自 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 但我不明白为什么这不起作用。 “从那时起:”部分正确显示信息。但是当 运行 "From outside:" 它打印未定义。这个问题与 response.on 嵌套在 request.on 中有什么关系吗?

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

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

您需要 return 在您的 on 类型事件处理程序中。详细了解异步代码和同步代码 here

试试这个,它可能适合你,

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

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

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