-1

I'm trying to return the results of an http request from a function and thought request-promise was supposed to return after an await. I obviously don't have this right. I get "undefined" returned from the function.

var s = getUrl();
console.log('result: ' + s)

function getUrl() {
    var rp = require('request-promise');
    var url = 'http://myserver.com?param=xxx';
    rp(url)
    .then(function (data) {
        return data;
    })
    .catch(function (err) {
        console.log(err);
    });
}

How do I await the call so getUrl returns the data?

EDIT: After Kevin's comment. I tried to put this into a module and call it but it's returning [object Promise].

function getUrl(url, params) {
    var rp = require('request-promise');
    return rp(url + '?' + params)
    .then(function (data) {
        return data;
    })
    .catch(function (err) {
        console.log(err);
    });
}


async function getUpdate(o) {
    var url = 'http://myserver.com';
    var params = 'param=xxx';
    var s = await getUrl(url, params);
    return s;
}

exports.askVelo = (o) => {
    var sRtn = '';
    
    console.log(o.code);

    switch (o.code) {
        case 'g':
            sRtn = getUpdate(o);
            break;
    }

    console.log('heres rtn: ' + sRtn);  // sRtn is [object Promise]
    return sRtn;
}

getUpdate is now just returning [object Promise]... Why is that not working now?

Velocedge
  • 1,222
  • 1
  • 11
  • 35
  • 1
    `rp(url)` becomes `return rp(url)`, then you can await `getUrl()` (as long as `getUrl` is called from an async function) – Kevin B Feb 25 '21 at 18:00
  • Awesome! That's works but I don't totally get why getUrl need to be called from an async function. I just wrapped it like async function xx() { s=await getUrl) and then called xx() – Velocedge Feb 25 '21 at 18:13
  • 1
    I would think that you need to `sRtn = await getUpdate(o)` as well. – ironcito Feb 25 '21 at 19:14
  • When using async/await, you gotta use it all the way up the chain or resort to using callbacks. Async/await effectively is syntactic sugar over using .then(). You can't transition from async/await to non-async/await without using .then, therefore you're better off just making it all async/await – Kevin B Feb 25 '21 at 19:18
  • Ironcito: I can await that because it's not inside an async function. Kevin: Ok, but I was able to call xx() and it worked. I'm trying to do this in a nodejs module in exports.askVelo which can't be async. So, how to I get the data out of askVelo? – Velocedge Feb 25 '21 at 19:41

1 Answers1

0

I really needed to get the data in a synchronous fashion, so I finally gave up and used sync-request and skipped all the await/promise stuff.

    sr = require('sync-request');
    var url = 'http://myserver';
    var qstring = 'param=xxx';
    var res = sr('GET', url + '?' + qstring);
    var str = res.body.toString();
Velocedge
  • 1,222
  • 1
  • 11
  • 35