在promise链上使用setTimeout [英] using setTimeout on promise chain
问题描述
在这里,我试图围绕promises.Here第一次请求我获取一组链接。在下一个请求我获取第一个链接的内容。但我想在返回下一个promise对象之前做出延迟。所以我在它上面使用了setTimeout。但是它给了我以下JSON错误( 没有setTimeout()它可以正常工作
)
Here i am trying to wrap my head around promises.Here on first request i fetch a set of links.and on next request i fetch the content of first link.But i want to make a delay before returning next promise object.So i use setTimeout on it.But it gives me the following JSON error (without setTimeout() it works just fine
)
SyntaxError:JSON.parse:
第1行第1行的意外字符JSON数据
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
我想知道它失败的原因?
i would like to know why it fails?
let globalObj={};
function getLinks(url){
return new Promise(function(resolve,reject){
let http = new XMLHttpRequest();
http.onreadystatechange = function(){
if(http.readyState == 4){
if(http.status == 200){
resolve(http.response);
}else{
reject(new Error());
}
}
}
http.open("GET",url,true);
http.send();
});
}
getLinks('links.txt').then(function(links){
let all_links = (JSON.parse(links));
globalObj=all_links;
return getLinks(globalObj["one"]+".txt");
}).then(function(topic){
writeToBody(topic);
setTimeout(function(){
return getLinks(globalObj["two"]+".txt"); // without setTimeout it works fine
},1000);
});
推荐答案
为了保持承诺链,你不能使用 setTimeout()
你的方式,因为你没有从 .then()
处理程序返回一个承诺 - 你从 setTimeout()
回调中返回它,这对你没有好处。
To keep the promise chain going, you can't use setTimeout()
the way you did because you aren't returning a promise from the .then()
handler - you're returning it from the setTimeout()
callback which does you no good.
相反,你可以做一个像这样的简单的小延迟函数:
Instead, you can make a simple little delay function like this:
function delay(t, v) {
return new Promise(function(resolve) {
setTimeout(resolve.bind(null, v), t)
});
}
并且,然后像这样使用它:
And, then use it like this:
getLinks('links.txt').then(function(links){
let all_links = (JSON.parse(links));
globalObj=all_links;
return getLinks(globalObj["one"]+".txt");
}).then(function(topic){
writeToBody(topic);
// return a promise here that will be chained to prior promise
return delay(1000).then(function() {
return getLinks(globalObj["two"]+".txt");
});
});
这里你要从 .then()返回一个承诺
处理程序,因此它被正确链接。
Here you're returning a promise from the .then()
handler and thus it is chained appropriately.
您还可以向Promise对象添加延迟方法然后直接在你的承诺上使用 .delay(x)
方法:
You can also add a delay method to the Promise object and then directly use a .delay(x)
method on your promises like this:
function delay(t, v) {
return new Promise(function(resolve) {
setTimeout(resolve.bind(null, v), t)
});
}
Promise.prototype.delay = function(t) {
return this.then(function(v) {
return delay(t, v);
});
}
Promise.resolve("hello").delay(500).then(function(v) {
console.log(v);
});
或者,使用已经 .del的蓝鸟承诺库。 ay()
内置方法。
Or, use the Bluebird promise library which already has the .delay()
method built-in.
这篇关于在promise链上使用setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!