[英]Value is always undefined returning from promise
I am currently working with the blackberry dynamics SDK. 我目前正在使用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. 我目前正在为SDK使用http请求功能,但是每次我想从http调用返回响应时,响应始终是未定义的-我试图使它返回一个值,但无济于事。
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. 提前加油。
As per @Nikos M. suggestion this is what ave done and now works as expected. 根据@Nikos M.的建议,这是已经完成的工作,现在可以按预期运行。
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));
});
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.