javascript - 来自较早承诺的控制台日志出现在来自最新承诺的控制台日志之后
问题描述
下面不是我的确切代码,但我只是想概述一下结构。当我运行代码时,我得到控制台日志的顺序是这样的:
- '完毕'
- json
我希望这会反过来,因为为了让 function2 完成(并发送“完成”解析值), function3 必须首先完成。
我想了解为什么它不能那样工作。
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
已经返回了一个承诺!
// ...
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
标题,因为它对GET
请求没有任何意义。)
推荐阅读
- python - 当值是python中的值列表时如何获取字典键
- swift - 使用随机初始密钥解码字典
- angular - 如何在 Angular 中为 FullCalendar 设置多个属性
- javascript - HTML 拖放 API IE11 问题
- node.js - Express(NodeJS)中具有动态参数匹配问题的网址
- angular - ng-bootstrap - 日期选择器的图标未显示
- c# - 使用现有文件的 EPPlus 更改数据透视表的范围
- jsrender - 使用双向数据绑定呈现由 ID 链接的两个数组
- leaflet - 无法删除传单多边形地图上的标记
- powershell - 尝试在 c:\ 上自动运行 chkdsk