lucky simon
lucky simon

Reputation: 291

Make a synchroneous request in NodeJS

I am trying to make a post request using NodeJS and request. I tried using promises and the async/await like other post says but I can manage to make work.

const express = require('express');
const bodyParser = require('body-parser');
var request = require("request");

const app = express();

app.use(bodyParser.json());

var token = '';
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;

function postRequest(options) {
    request(options, function (error, response, body) {
        if (error) throw new Error(error);

        token = (JSON.parse(body)).access_token;
        console.log(token + 'tet');
        return (token);
    });
}

async function requestToken() {
    var options = {
        method: 'POST',
        url: 'https://simplivity@xxxx/api/oauth/token',
        headers: { 'Content-Type': 'application/json' },
        formData:
        {
            grant_type: 'password',
            username: '[email protected]',
            password: 'xxxx'
        }
    };
    try {
        var test = await postRequest(options)
        return (test);
    } catch (error) {
        console.error(error);
    }
}

var test = requestToken();
console.log(test + 'TOT');

This is the answer :

[object Promise]TOT
00bd0beb-8967-4534-8c63-2e5d0d6876d4tet

Which should be the opposite.

thank you for your help.

Upvotes: 1

Views: 45

Answers (2)

Lars
Lars

Reputation: 447

(async () => {
  var test = await requestToken();
  console.log(test + 'TOT');
})();

While not very tidy something like this should work.

Better:

requestToken()
.then(response => {
  console.log(response);
});

Upvotes: 1

Hiren Ghodasara
Hiren Ghodasara

Reputation: 336

You need to return a promise.

Change your postRequest to:

function postRequest(options) {
    return new Promise(function(resolve, reject) {
        request(options, function (error, response, body) {
            if (error) throw new Error(error);

            token = (JSON.parse(body)).access_token;
            console.log(token + 'tet');
            resolve(token);
        });
    });  
}

Upvotes: 1

Related Questions