简体   繁体   English

在 ES6 fetch 调用中链接 .then 函数

[英]Chaining .then functions in ES6 fetch call

I have been looking for a way to figure this problem out and apologize if my searching skills are not up to par.我一直在寻找解决这个问题的方法,如果我的搜索技巧达不到标准,我深表歉意。

My Issue: I am fetching an API and I want to know when all of the data has been fully loaded.我的问题:我正在获取一个 API,我想知道所有数据何时都已完全加载。 Reading through the docs, it appears that I can chain .then statements with fetch and I thought that would work.通读文档,似乎我可以将 .then 语句与 fetch 链接起来,我认为这会起作用。 But, it appears that they all seem to fire at the same time without waiting for the previous .then to finish.但是,看起来它们似乎都在同时开火,而无需等待前一个 .then 完成。

Here's my code:这是我的代码:

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

This is great if it is asynchronous, but these events need to be synchronous due to the fact that I am trying to work with content that is created by the previous call, showSearchResults();如果它是异步的,这很好,但是由于我正在尝试处理由上一个调用 showSearchResults(); 创建的内容,因此这些事件需要同步。

Any help is much appreciated.任何帮助深表感谢。

Chaining a .then does not guarantee that code will execute sequentially unless you have returned a promise from the previous .then call.链接一个.then并不能保证代码会按顺序执行,除非您从前一个.then调用中返回了一个 promise。 In your example, if you want the second console.log to execute after showSearchResults , you should return showSearchResults() and chain your .then off of that (this only works if showSearchResults returns a promise; if it does not, you will want to wrap it in one similar to how you have for fetchStatus ).在您的例子,如果你想在第二console.log后执行showSearchResults ,你应该return showSearchResults()和链的.then了这一关(这只是工作,如果showSearchResults回报的承诺;如果没有,你会想将它包装成一个类似于fetchStatus )。

Similarly, if you want to chain a .then off of a setTimeout , you could write something like:同样,如果您想将.thensetTimeout ,您可以编写如下内容:

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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM