我正在学习浏览器提供的承诺,而我在回复论证中遇到困难却没有通过。这是我的代码:
/* 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! ' '
正如您所看到的,在successCallback(jqxhr)和响应函数之间,我的jqxhr变成了两个空格。发生了什么事?
答案 0 :(得分:0)
解释@Jaromanda X在评论中所说的内容。
您正在尝试解析另一个Promise
内的Promise
。原始Promise
对象不会传递给then
的回调。相反,它将是原始Promise
对象中的响应文本。
在这种情况下,jqxhr
是原始Promise
($.ajax
返回Promise
个对象),其响应文本为""
。这就是为什么你得到一个空字符串。
根据MDN的文档,您的代码与下面的示例相同
var original = Promise.resolve(true);
var cast = Promise.resolve(original);
cast.then(function(v) {
console.log(v); // true
});
**于11/14/16升级
@Bergi指出,jqxhr
不是Promise
的实例,而是具有属性then
(类似承诺)的JQuery延迟对象。但是,Promise.then
会查找jqxhr.then
,如果存在此类属性,则会异步解析promise。
答案 1 :(得分:0)
通过在验证函数中一直返回jQuery promise来修复它。