node js undefined value从http get async函数返回

时间:2018-03-10 21:11:01

标签: node.js async-await ecma

我正在尝试从异步函数获取http get响应。但是在函数值中显示但返回值未定义。

甚至承诺不是未定义的值

请找到以下代码

'use strict';
const express = require('express');
    var request = require('request');
var https = require('https');

async function getCurrencies() {
    let    response;
    try {


        var getOptions = {
            url: 'http://localhost:3000/api/currency',
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            },
            json:true
        };

        await request(getOptions, function (err, res, body) {

            if (res && (res.statusCode === 200 || res.statusCode === 201)) {
        console.log(' response ', res.body.rates.INR);

            return res.body;
            } else {
                console.log('error body ', body);

            }
        });

    } catch (error) {
        console.log(" error pulling ", error);
        process.exit();
    }

}

var tt =  getCurrencies().then(function(value) {
    console.log(' tt values ',value);

}
);

下面是日志

 tt values  undefined
 response 64.945

2 个答案:

答案 0 :(得分:3)

我会改写做类似的事情:

function getCurrencies() {

    return new Promise((resolve, reject) => {
        try {

            var getOptions = {
                url: 'http://localhost:3000/api/currency',
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                },
                json:true
            };

            request(getOptions, function (err, res, body) {

                if (res && (res.statusCode === 200 || res.statusCode === 201)) {
                    console.log(' response ', res.body.rates.INR);
                    resolve(res.body);
                } else {
                    console.log('error body ', body);
                    reject(new Error('Error body: ' + JSON.stringify(body)));
                }
            });

        } catch (error) {
            console.log(" error pulling ", error);
            process.exit();
        }
    });
}

getCurrencies().then(function(value) {
    console.log(' tt values ',value);
});

你也可以做一些更紧凑的事情:

const rp = require('request-promise');
function getCurrencies() {

    var getOptions = {
        url: 'http://localhost:3000/api/currency',
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        },
        json:true,
        resolveWithFullResponse: true 
    };

    return rp(getOptions).then((response) => {
        return response.body;
    });
}

getCurrencies().then(function(value) {
    console.log(' tt values ',value);
}).catch ((err) => {
    console.error('An error happened: ' + err);
});

答案 1 :(得分:0)

request模块/功能不会返回Promise,因此您无法使用await。您有两种选择:

  1. 使用标准节点回调模式或
  2. 切换到例如如果您坚持使用request-promise-native模式
  3. ,请async/await模块