在 ES6 fetch 调用中链接 .then 函数
Chaining .then functions in ES6 fetch call
我一直在寻找一种方法来解决这个问题,如果我的搜索技巧没有达到标准,我深表歉意。
我的问题: 我正在获取一个 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()
}
如果它是异步的,那就太好了,但是由于我正在尝试处理由之前的调用 showSearchResults();
创建的内容,因此这些事件需要同步
非常感谢任何帮助。
链接 .then
并不能保证代码将按顺序执行,除非您从之前的 .then
调用中返回了承诺。在您的示例中,如果您希望第二个 console.log
在 showSearchResults
之后执行,您应该 return showSearchResults()
并将您的 .then
链接起来(这仅在 showSearchResults
returns 一个承诺;如果没有,您将希望将其包装在一个类似于 fetchStatus
) 的承诺中。
类似地,如果你想从 setTimeout
链接 .then
,你可以这样写:
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!
我一直在寻找一种方法来解决这个问题,如果我的搜索技巧没有达到标准,我深表歉意。
我的问题: 我正在获取一个 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()
}
如果它是异步的,那就太好了,但是由于我正在尝试处理由之前的调用 showSearchResults();
创建的内容,因此这些事件需要同步非常感谢任何帮助。
链接 .then
并不能保证代码将按顺序执行,除非您从之前的 .then
调用中返回了承诺。在您的示例中,如果您希望第二个 console.log
在 showSearchResults
之后执行,您应该 return showSearchResults()
并将您的 .then
链接起来(这仅在 showSearchResults
returns 一个承诺;如果没有,您将希望将其包装在一个类似于 fetchStatus
) 的承诺中。
类似地,如果你想从 setTimeout
链接 .then
,你可以这样写:
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!