Search code examples
javascriptcallbackpromiseblackberry-dynamics

Value is always undefined returning from promise


I am currently working with the blackberry dynamics SDK.

I am currently using the http request functionality for the SDK but every time I want to return a response from a http call its always undefined - I tried promisifying it to return a value but to no avail.

It originally used two callbacks - which would rightly return me undefined, but if I make it a promise should it not return me a value.

Code

function constructGDHttpPostRequest(reqObj) {
    let PostRequest = window.plugins.GDHttpRequest.createRequest("POST", URI + reqObj.endPoint, 30, false);
    PostRequest.addRequestHeader('Content-Type', 'application/json');
    PostRequest.addHttpBody(reqObj.body);
    return SendRequest(PostRequest).then(function (httpRes) {
        console.log(httpRes);
        return httpRes;
    })
}

function SendRequest(Request) {
    return new Promise(function (resolve) {
        resolve(Request.send(sendSuccess));
    })
}

function sendSuccess(response) {
    console.log("Received valid response from the send request");
    let Response = window.plugins.GDHttpRequest.parseHttpResponse(response);
    return JSON.parse(Response.responseText);
}

I have tried using some of the questions asked relating to something like this but it still returned undefined from the promise.

Cheers in advance.


Solution

  • As per @Nikos M. suggestion this is what ave done and now works as expected.

    I needed to resolve the callback in order to return a value.

    I would like to make the callback a little cleaner with some suggestions.

       function constructGDHttpPostRequest(reqObj) {
            let PostRequest = window.plugins.GDHttpRequest.createRequest("POST", URI + reqObj.endPoint, 30, false);
            PostRequest.addRequestHeader('Content-Type', 'application/json');
            PostRequest.addHttpBody(reqObj.body);
            return SendRequest(PostRequest).then(function (httpRes) {
                console.log(httpRes);
                return httpRes;
            })
        }
    
        function SendRequest(Request) {
            return new Promise(function (resolve) {
                Request.send(function (response) {
                    resolve(JSON.parse(window.plugins.GDHttpRequest.parseHttpResponse(response).responseText));
                });
            })
        }