【问题标题】:Value is always undefined returning from promise从承诺返回的价值总是不确定的
【发布时间】:2018-11-26 15:45:38
【问题描述】:

我目前正在使用黑莓动态 SDK。

我目前正在使用 SDK 的 http 请求功能,但每次我想从 http 调用返回响应时,它总是未定义 - 我尝试承诺它返回一个值但无济于事。

它最初使用了两个回调 - 这将正确地返回我未定义的,但如果我将它作为一个承诺,它应该不会返回我一个值。

代码

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);
}

我已尝试使用与此类问题相关的一些问题,但它仍然返回未定义的承诺。

提前干杯。

【问题讨论】:

  • 为什么要做出这些不必要的承诺?
  • 我知道没有必要 - 我只是坚持了一堆,因为我无法从 sendSuccess 返回任何东西
  • 不管console.log(httpRes); 仍然返回 undefined 无论我做什么。
  • 当实际调用 sendSuccess 回调时,您应该 resolve。那是解决承诺的时候了,而不是在发起请求时解决

标签: javascript callback promise blackberry-dynamics


【解决方案1】:

根据@Nikos M. 的建议,这已经完成,现在按预期工作。

我需要解析回调才能返回一个值。

我想通过一些建议使回调更简洁。

   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));
            });
        })
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-24
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多