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: unexpected character at line 1 column 1 of the JSON data

100

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

推荐答案

为了让promise 链继续运行,你不能像以前那样使用setTimeout(),因为你没有从.then()处理程序返回promise ——你是从setTimeout()回调返回promise ,这对你没有好处.

相反,你可以做一个简单的延迟函数,如下所示:

function delay(t, v) {
   return new Promise(function(resolve) { 
       setTimeout(resolve.bind(null, v), t)
   });
}

然后,像这样使用它:

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()处理程序的promise ,因此它被适当地链接起来.


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

Or, use the Bluebird promise library which already has the .delay() method built-in.

Json相关问答推荐

在Jenkins中使用ReadJSON读取json子元素

json 字符串到 Postgres 14 中的表视图

匹配来自不同数组的值

使用 jq 从字符串列表开始创建对象

Powershell v7 文本背景突出显示

如何迭代、动态加载我的表单输入元素,然后在 React 中的表单提交上检索输入值?

如何在 Android Studio 中将 List 字段作为空列表[]返回?

Kotlin Android Room 处理 Moshi TypeConverter 中的空对象列表

如何将从嵌套 Select 返回的空值转换为空数组?

序列化为json时如何忽略空列表?

JSON extract\set 的 SQLite JSON1 示例

如何为名称/值 struct 创建 JSON 模式?

使用 JSONObject 在 Java 中为以下 struct 创建嵌套 JSON 对象?

JSON.NET JsonConvert 与 .NET JavaScriptSerializer

将 JSON 对象推送到 localStorage 中的数组

Jackson 没有使用 @JsonProperty 覆盖 Getter

将 CoffeeScript 项目转换为 JavaScript(不缩小)?

在 Java 中比较两个 JSON 文件的最佳方法

js 中奇怪的 JSON 解析行为,Unexpected token :

从 JSON 到 JSONL 的 Python 转换