lar*_*rns 5 javascript promise fetch-api
我看到人们将 fetch 方法包装在一个承诺中。我似乎无法理解这样做的好处?Fetch 本身会返回一个承诺,您可以从中提取您需要的内容。
let url = 'https://jsonplaceholder.typicode.com/users';
fetch(url)
.then(function(response){
//console.log(response.json());
return response.json();
})
.then(function(data){
console.log(JSON.stringify(data));
})
.catch(function(err){
//console.log(err);
err = 'this is an error';
console.log(err);
})
Run Code Online (Sandbox Code Playgroud)
与此相比
return new Promise((resolve, reject) => {
fetch(url)
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3810 次 |
| 最近记录: |