小编zad*_*ees的帖子

ES6 fetch 调用中链接 .then 函数

我一直在寻找一种方法来解决这个问题,如果我的搜索技能达不到标准,我深表歉意。

我的问题:我正在获取 API,我想知道所有数据何时已完全加载。通读文档,我似乎可以将 .then 语句与 fetch 链接起来,我认为这会起作用。但是,看起来它们似乎都同时开火,而没有等待前一个 .then 完成。

这是我的代码:

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()  
}
Run Code Online (Sandbox Code Playgroud)

如果是异步的,那就太好了,但这些事件需要同步,因为我正在尝试处理由先前调用 showSearchResults() 创建的内容;

任何帮助深表感谢。

javascript promise ecmascript-6 fetch-api

0
推荐指数
1
解决办法
3618
查看次数

标签 统计

ecmascript-6 ×1

fetch-api ×1

javascript ×1

promise ×1