0

This is probably a very basic question but none of the solutions online are helping. I am trying to make a post call

/* eslint-disable no-undefined */
let req = require('request');
function mutate(body) {
    return body;
}
function post(request) {
    let config = request.server.app.config;

    let payload = request.payload;
    let imageFile = '';
    let options = {
        method: 'POST',
        url: `${config.get('api.baseUrl')}/imageUpload`,
        headers: {
            'Accept': '*/*',
            'cache-control': 'no-cache'

        },
        formData:
        {
            file: imagefile

        }
    };

    return req(options, (error, response, body) => {
        if (error) {
            throw new Error(error);
        }
        request.log(response);
        return body;
    });
}
module.exports = {
    post
};

The response that is being printed is correct. The value is returned before the actual call completes. What is the correct method to return the actual response

Rohit
  • 1
  • 3

1 Answers1

0

to avoid your issue you can use

1) promises

2) async and await

please try to change your function as per below.

async function post (request) {
 let config = request.server.app.config;

let payload = request.payload;
let imageFile = '';
let options = {
    method: 'POST',
    url: `${config.get('api.baseUrl')}/imageUpload`,
    headers: {
        'Accept': '*/*',
        'cache-control': 'no-cache'

    },
    formData:
    {
        file: imagefile

    }
};

return await req(options, (error, response, body) => {
    if (error) {
        throw new Error(error);
    }
    request.log(response);
    return body;
});
}

you can check more info about async/await and promises here.

async-await usage

promises usage

Arif Rathod
  • 578
  • 2
  • 13