JS:嵌套承诺链还是将它们保持在同一范围内



这些基本上都做同样的事情吗?我在Promise的一个例子中遇到了这个问题,讲师已经返回了提取结果,但例子1不是另一种可行的方法吗?

1

fetch('url1')
.then(data => data.json())
.then(() => {
fetch('url2')
.then((response) => {
// do things
})
})

2

fetch('url1')
.then(data => data.json())
.then(() => {
return fetch('url2')

})
.then((response) => {
// do the same thing but at same scope
});

在示例1中,第二个then()解析为undefined

在示例2中,第二个then()采用了第二个fetch返回的promise,因此最终的then可以返回顶级返回值可用的东西。


不管怎样。这是一个非常冗长的代码,使用asyncawait可以更加清晰。

最新更新