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

时间:2021-01-14 20:18:55

标签: javascript node.js async-await

为什么第一个日志打印响应数据,第二个日志打印函数定义而不是响应数据。有没有办法调试和查看流程?

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

3 个答案:

答案 0 :(得分:0)

await 是一个与 Promise 值结合使用的关键字。它告诉代码等待 Promise 解析一个值,或者告诉它在出现错误时抛出。如果您检查 fetch 的函数定义,您将看到它直接返回一个 Promise 而不是响应对象。您需要使用 await 关键字来解析该 Promise。

const res = await fetch(...

答案 1 :(得分:0)

除了在调用 fetch 之前缺少 await 语句之外,还有其他一些原因。原因是因为 fetch 函数实际上返回一个承诺。

您将其设置为箭头函数。如果函数体只有一个表达式,箭头函数将执行隐式返回。所以 fetch 函数返回 https.get() 函数调用的结果,这只是函数签名,因为它与回调概念一起工作。

此外,您没有正确处理事件侦听器,因为 res.on('data', <function here>) 行没有返回承诺,因此 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");

我希望这个解释的尝试有帮助!

答案 2 :(得分:0)

找到了。貌似 https 没有返回任何东西,你可以在请求完成后使用 Promise/resolve 返回响应。

import React, { Component } from 'react';
import { connect } from 'react-redux';


class UsersListConainer extends Component {
    componentDidMount() {
        this.props.getStats();
        this.props.getUsers();
     }
     .......
     ........

     render() {
        const { usersData, userStats } = this.props;

        return (
            <>
                <Stats data={userStats} />
                <Table data={usersData} />
            </>
        );
   }
}

const mapStateToProps = (state) => {
    const { usersData, userStats } = state.users;
    return {
        usersData,
        userStats
    };
 };

 export default connect(mapStateToProps, null)(UsersListConainer);