微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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 解析一个值,或者告诉它在出现错误时抛出。如果您检查 fetch 的函数定义,您将看到它直接返回一个 Promise 而不是响应对象。您需要使用 await 关键字来解析该 Promise。

const res = await fetch(...
,

除了在调用 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");

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

,

找到了。貌似 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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?