Javascript 有什么区别?异步与嵌套承诺语句
我只是在更新我对JS世界中某些事物的知识和理解。有没有人能告诉我以下两种方法有什么不同 梦魇Javascript 有什么区别?异步与嵌套承诺语句,javascript,node.js,asynchronous,Javascript,Node.js,Asynchronous,我只是在更新我对JS世界中某些事物的知识和理解。有没有人能告诉我以下两种方法有什么不同 梦魇 // Nested nightmare fetch('https://jsonplaceholder.typicode.com/todos/1') .then(json1 => json1.json()) .then(res1 => { console.log("======== 1 ======") console.log(res1)
// Nested nightmare
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(json1 => json1.json())
.then(res1 => {
console.log("======== 1 ======")
console.log(res1)
fetch(`https://jsonplaceholder.typicode.com/todos/${res1.id+1}`)
.then(json2 => json2.json())
.then(res2 => {
console.log("======== 2 ======")
console.log(res2)
fetch(`https://jsonplaceholder.typicode.com/todos/${res2.id+1}`)
.then(json3 => json3.json())
.then(res3 => {
console.log("======== 3 ======")
console.log(res3)
})
})
})
异步等待
// Using async await
const getData = async (id) => {
return await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
.then(json => json.json())
.then(res => res)
}
const res_1 = await getData(1).then(res => {
console.log("======== 1 ======")
console.log(res)
return res
})
const res_2 = await getData(res_1.id + 1).then(res => {
console.log("======== 2 ======")
console.log(res)
return res
})
const res_3 = await getData(res_2.id + 1).then(res => {
console.log("======== 3 ======")
console.log(res)
return res
})
编辑:我应该提到的是,每一项的结果都依赖于前一项的响应。第一个的结果需要与最后一个的结果进行比较,嵌套的噩梦可以重写为:
fetch('https://jsonplaceholder.typicode.com/todos/1').then(json1 => json1.json())
.then(res1 => {
console.log("======== 1 ======")
console.log(res1)
return fetch(`https://jsonplaceholder.typicode.com/todos/${res1.id+1}`).then(json2 => json2.json());
}).then(res2 => {
console.log("======== 2 ======")
console.log(res2)
return fetch(`https://jsonplaceholder.typicode.com/todos/${res2.id+1}`).then(json3 => json3.json());
}).then(res3 => {
console.log("======== 3 ======")
console.log(res3)
});
这看起来不像是一场“噩梦”,更能说明两者之间的等价性。这是一场“嵌套承诺噩梦”,因为这不是你应该如何使用承诺。在工作方式上,几乎没有什么区别,尽管async/await更容易阅读和理解。还有你的“async await”code也错误地使用了Promission,因为当您使用
await
时,您不需要使用,那么@Dai他可能在控制台日志中使用它。@Baruch这仍然是不必要的await promise;console.log()
仍然是等效的,而不是混合使用。如果有一个助手fetchAsJSON=(url)=>fetch(url)。那么(resp=>resp.json())
(如果它们真的共享相同的baseURI,甚至可能是生成url的另一个)无论如何,Promission和async/await之间的主要区别在于它如何处理try
/catch
:对于Promissions,如果链中第一个调用的函数抛出,您必须用try
/catch
捕捉它,但是如果它发生在链中,它将被第二个参数.then
或.catch
捕获(您可以使用Promise.resolve()
启动链,但我觉得很奇怪)。使用async/await没有这种区别。我现在喜欢承诺,因为我不必太多考虑向后兼容性(有库)。