作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这个问题在这里已经有了答案:
What is the explicit promise construction antipattern and how do I avoid it?
(3 个回答)
2年前关闭。
下面不是我的确切代码,但我只是想概述一下结构。当我运行代码时,我得到控制台日志的顺序是这样的:
function1().then(() => {
return function2()
).then((message) => {
console.log(message)
})
function function2() {
return new Promise((resolve, reject) => {
fetch(url, {
method: 'get',
body: null,
headers: {
"Content-Type": "application/json; charset=UTF-8",
"Accept": "application/json; charset=UTF-8",
},
})
.then(res => res.json())
.then((json) => {
return function3(json)
})
resolve('Done')
})
}
function function3(json) {
console.log(json)
}
最佳答案
您调用resolve
在您的 fetch
之前甚至完成。
如果你把它移到另一个 then
就行了:
// ...
.then(res => res.json())
.then((json) => {
return function3(json)
})
.then(() => {
resolve('Done')
})
但其实整个
new Promise
甚至没有必要因为
fetch
已经返回了一个 promise !
// ...
function function2() {
return fetch(url, { // It's important to actually *return* the promise here!
method: 'get',
body: null,
headers: {
"Content-Type": "application/json; charset=UTF-8",
"Accept": "application/json; charset=UTF-8"
}
})
.then(res => res.json())
.then((json) => {
return function3(json)
})
.then(() => {
return 'Done'
})
}
这可以使用
async
进一步简化。/
await
:
// I moved this into a function because the global module-level code
// is not in an async context and hence can't use `await`.
async function main () {
await function1()
console.log(await function2())
}
async function function1 () {
// I don't know what this does, you didn't include it in your code snippet
}
async function function2 () {
const response = await fetch(url, {
method: 'get',
body: null,
headers: {
"Accept": "application/json; charset=UTF-8"
}
})
const json = await response.json()
await function3(json)
return 'Done'
}
// At the moment this wouldn't have to be async because you don't do anything
// asynchronous inside, but you had `return function3(json)` in the original code,
// so I assume it is *going* to be async later.
async function function3 (json) {
console.log(json)
}
// Don't forget to .catch any rejections here! Unhandled rejections are a pain!
main().catch(console.error)
(当我这样做时,我删除了
Content-Type
header ,因为它对
GET
请求毫无意义。)
关于javascript - 来自较早 promise 的控制台日志出现在来自最新 promise 的控制台日志之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63092483/
我想在 tomcat 加载 servlet 并准备好服务时在启动时收到通知。我想在此通知中对此 servlet 进行 http 调用。 我已经尝试将 ServletContextListener 添加
我是一名优秀的程序员,十分优秀!