使用setTimeout在promise链上

12 浏览
0 Comments

使用setTimeout在promise链上

在这里,我试图理解Promise。在第一个请求上,我获取一组链接,然后在下一个请求上获取第一个链接的内容。但我想在返回下一个promise对象之前延迟一下。所以我在它上面使用了setTimeout。但是它给我返回以下JSON错误(没有使用setTimeout()时它运行得很好

SyntaxError: JSON.parse:在JSON数据的第1行第1列找到意外字符

我想知道为什么它失败了?

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);
});

0