这些基本上都做同样的事情吗?我在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
可以返回顶级返回值可用的东西。
不管怎样。这是一个非常冗长的代码,使用async
和await
可以更加清晰。