简体   繁体   English

如何在 https 模块上使用 await 以在 node.js 中获得响应

[英]How to use await on https module to get response in node.js

why does the 1st log print response data, and 2nd log prints function definition instead of response data.为什么第一个日志打印响应数据,第二个日志打印 function 定义而不是响应数据。 is there a way to debug and see the flow?有没有办法调试和查看流程?

const https = require("https");
const substr = "spider";
const pageNum = 1;

let list = [];

const fetch = (url) =>
  https.get(url, async (res) => {
    res.setEncoding("utf-8");
    let ttt;
    await res.on("data", function (data) {
      ttt = data;
    });
    console.log(ttt); //1st log
    return ttt;
    
  });

  
((substr) => {
  totalPages = 1;

  pageNum;
  for (let i = 1; i <= totalPages; i++) {
    const res = fetch(
      "https://jsonmock.hackerrank.com/api/movies/search/?Title=" +
        substr +
        "&page=" +
        i
    );
    console.log(res);//2nd log
  }
})("s");

await is a keyword that is used in combination with a Promise value. await 是与 Promise 值结合使用的关键字。 It tells the code to wait until the Promise resolves a value, or tells it to throw if there is an error.它告诉代码等到 Promise 解析一个值,或者告诉它如果有错误就抛出。 If you check the function definition for fetch you will see that it returns a Promise instead of the response object directly.如果您检查 function 的 fetch 定义,您将看到它返回 Promise 而不是直接响应 object。 You need to use the await keyword to resolve that Promise.您需要使用 await 关键字来解析 Promise。

const res = await fetch(...

You are not awaiting the fetch request in the loop.您没有在循环中等待获取请求。 Res just holds the Promise that fetch returns. Res 只保存 fetch 返回的 Promise。 You instead need to have a try and catch block around the statement with an await before the fetch call or you simply use.then() and.catch().相反,您需要在语句周围有一个 try 和 catch 块,并在 fetch 调用之前等待,或者您只需使用.then() 和.catch()。

There are some more reasons besides the missing await statement before the call to fetch.除了调用 fetch 之前缺少 await 语句之外,还有其他一些原因。 The reason is because the fetch function does not in fact return a promise.原因是提取 function 实际上并没有返回 promise。

You set it as an arrow function.您将其设置为箭头 function。 Arrow functions will do an implicit return if the function body only has a single expression.如果 function 主体只有一个表达式,箭头函数将执行隐式返回。 So the fetch function returns the result of the https.get() function call, which is just the function signature as it works with the callback concept. So the fetch function returns the result of the https.get() function call, which is just the function signature as it works with the callback concept.

Additionally you did not handle the event listener correctly, as the res.on('data', <function here>) line does not return a promise, so the await keyword did not do anything.此外,您没有正确处理事件侦听器,因为res.on('data', <function here>)行不返回 promise,因此 await 关键字没有做任何事情。

Let's see how I would rewrite your code to run as expected:让我们看看我将如何重写您的代码以按预期运行:

const https = require('https')
const substr = 'spider'
const pageNum = 1

let list = []

// Create an async function fetch that takes the url
const fetch = (url) => {
  // Return a promise
  return new Promise((resolve, reject) => {
    // Call the https.get function
    https.get(url, (res) => {
      res.setEncoding('utf-8')
      // Set the event listener
      res.on('data', function (data) {
        // Here the actual data event is _happening_. Now we have the return value
        console.log(data) // 1st Log
        resolve(data)
      })
    })
  })
}

(async (substr) => {
  totalPages = 1;

  pageNum;
  for (let i = 1; i <= totalPages; i++) {
    // await the promise returned from fetch
    const res = await fetch(
      "https://jsonmock.hackerrank.com/api/movies/search/?Title=" +
      substr +
      "&page=" +
      i
    );
    console.log(res);//2nd log
  }
})("s");

I hope this attempt at an explanation helps!我希望这种解释尝试有所帮助!

found it.找到了。 looks like https doesn't return anything, you can use Promise/resolve to return response after the request is completed.看起来 https 没有返回任何内容,您可以在请求完成后使用 Promise/resolve 返回响应。

const https = require("https");
const substr = "spider";
const pageNum = 1;

let list = [];


const fetch = async (url) => {
  return new Promise((resolve) => {
    https.get(url, async (res) => {
      res.setEncoding("utf-8");
      let ttt;
      await res.on("data", function (data) {
        ttt = data;
        resolve(data);
      });
      res = ttt;
      console.log(ttt);
    });
  });
};

(async (substr) => {
  totalPages = 1;

  pageNum;
  for (let i = 1; i <= totalPages; i++) {
    const res = await fetch(
      "https://jsonmock.hackerrank.com/api/movies/search/?Title=" +
        substr +
        "&page=" +
        i
    );
    console.log(res);
  }
})("s");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM