gpt4 book ai didi

javascript - Promise 的创建是同步的吗?

转载 作者:行者123 更新时间:2023-11-29 18:43:16 25 4
gpt4 key购买 nike

我需要编写一个函数来进行两个链接的 HTTP 调用,并在第二次调用的结果可用时对结果采取行动。

我认为可行的方法是

function getdata() {
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(r => r.json())
.then(r => fetch(`https://jsonplaceholder.typicode.com/todos/2`)
.then(s => s.json())
)
}
let m = getdata()
m.then(x => console.log(JSON.stringify(x)))

这工作正常,控制台输出符合预期。

然后我将这个想法移植到我的实际调用中,主要区别在于 HTTPS 调用很慢。为了将实际错误映射到代码,请考虑上面代码的一个小变体(添加了一些日志记录)

function getdata() {
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(r => r.json())
.then(r => fetch(`https://jsonplaceholder.typicode.com/todos/2`)
.then(s => {
console.log(s)
s.json()
})
)
}
let m = getdata()
m.then(x => console.log(x))

控制台输出(来 self 的实际代码)类似于

11:36:56.388 undefined
11:36:56.456 filter-sentinels.js:42 Response {type: "cors", url: …}

详细信息:

  • 第一个 undefined 来自 console.log(x)
  • 第二行来自console.log(s)

Promise 似乎是在第一行之后的第二行中解决的。这很正常,这就是 promise 的用途。

我不明白的是为什么执行m.then(x => console.log(x) ))中的.then()什么时候 promise 还没有解决?

关于标题的注释:我真正想了解的是我是否可以将正在生成的 Promise (let m = ...) 视为同步的东西——从某种意义上说,我可以安全地对其应用 then(),当相关信息已知(HTTP 调用已返回)时,then() 中发生的事情将发生。

最佳答案

问题是内嵌的 fetch 中有一个 Promise 没有与外部的 s.json() 链接:

.then(s => {
console.log(s)
s.json() // <---- This is not being returned; the Promise chain will resolve to undefined
})

你只是声明 s.json() Promise,但你没有返回它,也没有使用它,所以整个 getdata() Promise 解析为 undefined,一旦来自 /totos/2 的响应返回。

返回最终的嵌套 .json() 调用,它按预期工作:

function getdata() {
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(r => r.json())
.then(r => fetch(`https://jsonplaceholder.typicode.com/todos/2`)
.then(s => {
console.log(s)
return s.json()
})
)
}
m = getdata()
m.then(x => console.log(x) )

关于javascript - Promise 的创建是同步的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55513735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com