javascript - 需要在http响应后运行该变量

标签 javascript ecmascript-6 async-await es6-promise

我有一个 es6 类,从那里我将获得用户名和联系方式。在代码本身中,我提到了这个问题。

user1.getUserName()函数中,我将得到Mr.undefined。我知道原因是因为这一行 let str = 'Mr.' + username.name 在 http 调用之前执行。需要在http请求加载完成后运行该变量。

我尝试了很多找不到正确的解决方案。我认为我们可以用 promise 解决这个问题,但我不知道如何实现它。

const http = require('http');

class User {
    httpRequest () {
    http.get(url, function (resp) {
        let data = ''
      resp.on('data', (chunk) => {
        data += chunk
      })
      resp.on('end', () => {
        return JSON.parse(data)
      })
    })
  }

  getUserName () {
    let username = this.httpRequest()

    // needs to run after the http response

    let str = 'Mr.' + username.name
    return str;
  }

  getContactetail () {
    let contactDetail = this.httpRequest()
    let str = 'My address is ' + contactDetail.address
    return str;
  }
}

let user1 = new User();
console.log(user1.getUserName());

最佳答案

您还可以在出现错误时拒绝 httpRequest 方法内的 promise 。

class User {
    httpRequest () {
        return new Promise((resolve,reject)=>{
            http.get(url, function (resp) {
                let data = ''
              resp.on('data', (chunk) => {
                data += chunk
              })
              resp.on('end', () => {
                resolve(JSON.parse(data));
              })
            })

        })
  }

  getUserName async () {
    let username = await this.httpRequest()

    // needs to run after the http response

    let str = 'Mr.' + username.name
    return str;
  }

  getContactetail () {
    let contactDetail = this.httpRequest()
    let str = 'My address is ' + contactDetail.address
    return str;
  }
}

let user1 = new User();
console.log(user1.getUserName());

关于javascript - 需要在http响应后运行该变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58837035/

相关文章:

javascript - 破解 Alexa 以支持 AngularJS

javascript - 如何在 For...of 循环中替换数组中的所有 NaN 值

javascript - 使用 async beforeAll 时 test.each 全局中 undefined variable - Jest 24

javascript - 数组数据在嵌套的异步箭头函数循环中丢失

javascript - 为什么等待代码完成时等待不起作用

c++ - Intel TBB中如何有一个长时间等待的线程?

javascript - MomentJS,如何忽略用户的本地时区,并使用

javascript - 一种确定窗口大小并在为真时打开 javascript/jquery 代码的方法,如果不为真则关闭

javascript - axios 删除后台未收到的req.body

javascript - 未捕获的语法错误 : Unexpected identifier when trying to import React