代码之家  ›  专栏  ›  技术社区  ›  zadees

链接。然后ES6 fetch调用中的函数

  •  0
  • zadees  · 技术社区  · 8 年前

    我正在获取一个API,我想知道所有数据何时都已完全加载。通过阅读文档,我似乎可以链接。然后是fetch语句,我认为这会起作用。但是,它们似乎都在同一时间开火,而不必等待前一个。然后完成。

    这是我的代码:

    fetch(myUrl, {
        method: 'post',
        headers: {
           'Content-Type': 'application/json; charset=utf-8',            
         },
        credentials: 'include',         
        body: data
        })                                
            .then(fetchStatus)  
            .then(json)  
            .then(function(msg){                                    
                showSearchResults();
                setTimeout(function(){ console.log("Next then should fire after this"); }, 4000);                                   
            })
            .then(function(){
                return console.log("The 2nd is firing!");                                  
            });
    
    function fetchStatus(response) {  
        if (response.status >= 200 && response.status < 300) {  
            return Promise.resolve(response)  
        } else {  
            return Promise.reject(new Error(response.statusText))  
        }  
    }
    
    function json(response) {  
        return response.json()  
    }
    

    非常感谢您的帮助。

    1 回复  |  直到 8 年前
        1
  •  3
  •   dillonius01    8 年前

    链接a .then 呼叫在你的例子中,如果你想要第二个 console.log 之后执行 showSearchResults ,你应该 return showSearchResults() .然后 显示搜索结果 返回承诺;如果没有,您将希望将其包装在一个类似于您的 fetchStatus

    类似地,如果您想链接 .然后 关闭a setTimeout ,你可以这样写:

    fetch(url, { method: 'post', etc... })
       .then(fetchStatus)
       .then(json)
       .then(function(msg){
          return new Promise(function(resolve, reject){
             setTimeout(function() {
                console.log("Next then fires after promise resolves");
                resolve();
             }, 4000)
           })
        })
        .then(function(){
           console.log("Second is firing")
        })
        .catch(err => console.log(error)) // always remember to catch errors!
    
    推荐文章