我正在学习由浏览器提供的 Promise,并且在处理响应参数时遇到了困难,导致它无法返回。这是我的代码:
以下是我运行时得到的调试输出:
/* uploads a resource to the given server and runs the callback function when done */
function upload(serverUrl, resource, successfulCallback, failCallback) {
console.log("upload successfulCallback: ", successfulCallback);
console.log("upload failCallback: ", failCallback);
var jqxhr = $.ajax({
url: serverUrl,
method: "POST",
type: "POST",
contentType: "application/json",
data: encode(resource),
headers: {
Accept: "application/json; charset=utf-8",
Prefer: "return=minimal"
}
}).done(function() {
console.log("Upload done, jqxhr: ", jqxhr);
successfulCallback(jqxhr);
}).fail(function(err) {
console.log("upload failed: " + err.responseText);
failCallback(jqxhr, err);
});
}
function validate(endpoint, resource) {
var parameters = {
"resourceType": "Parameters",
"parameter": [{
"name": "resource",
"resource": resource
}]
};
return new Promise(function (resolve, reject) {
console.log("Made new promise, resolve function is: ", resolve);
console.log("Made new promise, reject function is: ", reject);
upload(endpoint + '/' + resource.resourceType + "/$validate", parameters, resolve, reject);
});
}
这是我如何使用它:
validate("http://fhir3.healthintersections.com.au/open", decode(leftFhirView.getValue()))
.then(function(response) {
console.log("It worked! '", response, "'");
}, function(error) {
console.error("Failed validation!", error.stack);
});
main.js:45 Made new promise, resolve function is: u() { [native code] }
main.js:46 Made new promise, reject function is: v() { [native code] }
main.js:14 upload successfulCallback: u() { [native code] }
main.js:15 upload failCallback: v() { [native code] }
main.js:27 Upload done, jqxhr: Object {readyState: 4, responseText: "", <snip>
main.js:196 It worked! ' '
你可以看到,在 successfulCallback(jqxhr) 和 response 函数之间,我的 jqxhr 变成了两个空格。发生了什么事情?
typeof response
来查看你正在解析的内容 -responseText
是一个空字符串,但你的代码仍然应该解析为在第27行记录的jqxhr对象。 - Jaromanda Xupload
函数内部创建一个new Promise
,并从那里return
它,这样你就不必处理回调参数了。 - Bergi