簡體   English   中英

如何在 https 模塊上使用 await 以在 node.js 中獲得響應

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

為什么第一個日志打印響應數據,第二個日志打印 function 定義而不是響應數據。 有沒有辦法調試和查看流程?

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 是與 Promise 值結合使用的關鍵字。 它告訴代碼等到 Promise 解析一個值,或者告訴它如果有錯誤就拋出。 如果您檢查 function 的 fetch 定義,您將看到它返回 Promise 而不是直接響應 object。 您需要使用 await 關鍵字來解析 Promise。

const res = await fetch(...

您沒有在循環中等待獲取請求。 Res 只保存 fetch 返回的 Promise。 相反,您需要在語句周圍有一個 try 和 catch 塊,並在 fetch 調用之前等待,或者您只需使用.then() 和.catch()。

除了調用 fetch 之前缺少 await 語句之外,還有其他一些原因。 原因是提取 function 實際上並沒有返回 promise。

您將其設置為箭頭 function。 如果 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.

此外,您沒有正確處理事件偵聽器,因為res.on('data', <function here>)行不返回 promise,因此 await 關鍵字沒有做任何事情。

讓我們看看我將如何重寫您的代碼以按預期運行:

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

我希望這種解釋嘗試有所幫助!

找到了。 看起來 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