fetch('url1')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data1 => {
// 这里使用data1进行第二个请求
return fetch('url2', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ data1 })
});
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data2 => {
// 这里使用data2进行第三个请求
return fetch('url3', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ data2 })
});
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data3 => {
console.log('Final data:', data3);
})
.catch(error => {
console.error('Error:', error);
});
使用Promise链式调用而不是简单嵌套写法的原因
- 可读性更高:链式调用将多个异步操作按顺序排列,代码结构更清晰,一目了然。相比之下,嵌套写法会导致“回调地狱”,随着异步操作的增多,代码会变得极其难以阅读和维护。
- 错误处理更统一:在链式调用中,可以通过一个
catch
块捕获整个链中任何位置抛出的错误,而嵌套写法需要在每个嵌套的回调中单独处理错误,代码重复且繁琐。
- 代码简洁性:链式调用避免了大量嵌套的代码块,使代码更加简洁,减少了冗余。