如何在第一次通话后重新调用承诺?
我遇到此问题,.then
仅在第一次点击后执行一次,之后您不会在任何点击后执行此console.log("Success!", response);
。但我需要它来回收。有可能吗?
用法:
$( document ).ready(function() {
get('http://api.icndb.com/jokes/random').then(function(response) {
console.log("Success!", response);
}, function(error) {
console.error("Failed!", error);
});
});
承诺功能:
function get(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
$(".promise").click(function(){
// do lots of other stuff here...
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
});
}
HTML,
<a href="#" class="promise">Promise</a>
答案 0 :(得分:1)
正如我在评论中所解释的那样,承诺只能使用一次。一旦解决或拒绝,它的状态将永久设置,并且永远不会再次调用现有的.then()
处理程序。因此,每次事件发生时,您都不能对希望调用的内容使用承诺。你可能会回到这样的回调,这似乎非常适合这种情况:
$( document ).ready(function() {
get('http://api.icndb.com/jokes/random', function(response) {
console.log("Success!", response);
}, function(error) {
console.error("Failed!", error);
});
});
function get(url, success, fail) {
$(".promise").click(function(){
// do lots of other stuff here...
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
success(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
fail(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
fail(Error("Network Error"));
};
// Make the request
req.send();
});
}
答案 1 :(得分:1)
编写自己的promisified get()
函数没有任何问题,这正是jQuery的$.ajax()
或Angular的$http
(和其他人)给你的。
您需要做的就是稍微重新排列代码,以便:
get()
是一个通用实用程序,与特定事件无关get()
根据需要从事件处理程序中调用。$(function() {
function get(url) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
} else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
});
}
$(".promise").click(function() {
// do lots of other stuff here...
get('http://api.icndb.com/jokes/random').then(function(response) {
console.log("Success!", response);
}, function(error) {
console.error("Failed!", error);
});
});
});
我在这里所做的就是将你的代码行移到不同的顺序。