最近我在早期的jQuery Promises / A模式中读到了article的缺点:
jQuery(1.8之前的)这样的库不会这样做:它们只是变异 现有承诺的状态。这意味着如果你做出承诺 对多个消费者来说,他们可以干涉其状态。至 实现多么荒谬,考虑同步并行:if 你把一个函数的返回值给了两个人,其中一个 可能会以某种方式将其变成抛出的异常!
我想用代码来实现这个缺点,我试过了:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
var promise = $.get("http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js");
var promise1 = promise.then(function (result) {
return "Hello";
});
promise1.then(function (result) {
console.log("in promise1 ------>", result.length);
})
var promise2 = promise.then(function (result) {
return "World";
})
promise2.then(function (result) {
console.log("in promise2 ------>", result.length);
})
</script>
</head>
...
似乎不起作用,我怎样才能实现上述文章的情况?
答案 0 :(得分:1)
这样的事情在1.8之前无法使用.then
- 只有.pipe
:
function doStuff() {
promptAsync("What url you want to fetch?").then(function (url) {
return $.get(url)
}).then(function (contents) {
return confirmAsync("Here are the contents " + contents + ". Is this ok?")
}).then(function (confirmation) {
if (!confirmation) {
return doStuff();
}
return alertAsync("I am glad you are happy with these results");
});
}
这与同步相同:
function doStuff() {
var url = prompt("What url you want to fetch?");
var contents = $.get(url);
var confirmation = confirm("Here are the contents " + contents + ". Is this ok?");
if (!confirmation) {
doStuff();
} else {
alert("I am glad you are happy with these results");
}
}
当然,即使在1.8之后,承诺.fail
也无法提供任何错误,但会导致您的网页崩溃。