在這裏,我試圖圍繞promise承擔我的頭。在第一次請求時,我獲取一組links.and下一個請求我獲取第一個鏈接的內容。但是我想在返回下一個承諾object.So我上它。但是它給了我下面的JSON錯誤(without setTimeout() it works just fine
)在承諾鏈上使用setTimeout
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
我想知道爲什麼它沒有使用的setTimeout?
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);
});
請注意,'return'是函數特有的,只返回父函數,並且不能從異步方法返回。 – adeneo
注意有很多[更好的方法](http://stackoverflow.com/q/28250680/1048572)來構造這個代碼,而不是使用'globalObj'。 – Bergi
'JSON.parse'扔在哪裏?我很難相信在一個「then」回調中是否存在'setTimeout'會影響前一個'then'回調中的調用。 – Bergi