简体   繁体   English

我似乎无法弄清楚为什么我在 console.log 在 async/await function

[英]I can't seem to figure out why I get 'undefined' after I console.log a value after an async/await function

I'm new to Node JS and I can't seem to figure out why i'm getting an 'undefined' when using an async function.我是 Node JS 的新手,我似乎无法弄清楚为什么在使用异步 function 时会出现“未定义”。 I've wrapped the async function in a promise and it resolves after an API request has been completed.我已将异步 function 包装在 promise 中,并在 API 请求完成后解决。

   let req = (url) => new Promise((resolve, reject) => {
    var options = {
        'method': 'GET',
        'url': url,
        'headers': {
            'Content-Type': 'application/json'
        }
    }

    request(options, function (error, response) { 
        if (error) {
            reject(error)
        } else {
            resolve(response.body)
        }
    })
})
.then((results) => {
    //console.log(results) //this shows the results when uncommented!
    console.log('request has been completed')
})
.catch((error) => {
    console.log(error)
})

Here is the function that triggers the 'req' function and then says 'undefined' when I log the value:这是触发'req' function 的 function ,然后在我记录值时说'未定义':

let getAllData = async (url) => {
    var endpoint = `${url}?apikey=${settings.api_key}`
    let res = await req(endpoint)
    console.log('run after request') //successfully runs after request is resolved above
    console.log(res) //gives me 'undefined' 

}

Here is my output.这是我的 output。

request has been completed
run after request
undefined

What am I doing wrong here?我在这里做错了什么?

You are using a.then /.catch as part of the function definition - which does not make sense.您正在使用 a.then /.catch 作为 function 定义的一部分 - 这没有意义。 Those constructs should be used as part of the function execution.这些构造应该用作 function 执行的一部分。

Define your function like this:像这样定义您的 function :

let req = (url) => new Promise((resolve, reject) => {
    var options = {
        'method': 'GET',
        'url': url,
        'headers': {
            'Content-Type': 'application/json'
        }
    }

    request(options, function (error, response) { 
        if (error) {
            reject(error)
        } else {
            resolve(response.body)
        }
    })
})

Then, at execution time, you do this:然后,在执行时,您执行以下操作:

let getAllData = async (url) => {
    var endpoint = `${url}?apikey=${settings.api_key}`
    let res = await req(endpoint)

    console.log('run after request')
    console.log(res) // should give response.body 

}

OR you do this:或者你这样做:

let getAllData = async (url) => {
    return new Promise((resolve, reject) => {
        var endpoint = `${url}?apikey=${settings.api_key}`
        req(endpoint)
        .then(res => {
            console.log('run after request')
            console.log(res) // should give response.body

            resolve(res)
        })
        .catch(err => {
            console.error(err)
            reject(err)
        })
    })
}

Basically, define the function and then... either call it with async/await syntax, or with promise-style.then/.catch syntax.基本上,定义 function 然后......要么用 async/await 语法调用它,要么用 promise-style.then/.catch 语法调用它。

Return a value in your then or remove the then and catch block and do this instead when you call the promise with await:then中返回一个值或删除 then 和 catch 块,并在您使用 await 调用 promise 时执行此操作:

let res = await req(endpoint).catch(err => console.log(err));

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

相关问题 等待后,console.log 不返回异步结果 - console.log doesn't return result in async after await 为什么我无法从Mogoose的Model.find()使用console.log输出结果? - Why I can't output the result with console.log from Mogoose's Model.find()? 为什么在console.log()中看不到socket.io的服务器代码? - Why can't I see in console.log() the server code of socket.io? 当我安慰 console.log 时,我得到了未定义 - i got undefined when i consoled console.log 我的CPU在Google Cloud上的使用率已达到160%,我似乎不知道为什么吗? - My CPU is reaching 160% on Google Cloud and I can't seem to figure out why? 我在Node.JS中得到一个SyntaxError,但我无法从日志消息中找出该错误的来源 - I get a SyntaxError in Node.JS, but I can't figure out the origin of that error from the log messages web 抓取 function 返回“未定义”,但在我使用 console.log 时有效 - web scraping function returns “undefined” but works when I use console.log 为什么我在 bcrypt compare 上遇到错误? 异步/等待函数 - why do i get an error on bcrypt compare? async/await function 为什么我无法通过同步等待从异步等待中获得价值? - Why I cannot get value from async await by waiting synchronously? 如何与.on同时调用console.log和console.log()? - How can I invoke console.log and console.log() simultaneously with .on?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM