【发布时间】:2020-10-11 06:06:45
【问题描述】:
我继续练习 JS。
这一次,我尝试使用 async / await 或 promise 做同样的事情:
const url = 'https://jsonplaceholder.typicode.com/todos/1';
- 异步/等待版本:
async function getData() {
const response = await fetch(url);
const data = await response.json();
return data;
}
const callGetData = async () => {
try {
const data = await getData()
console.log(data);
} catch (error) {
console.log("Something gone wrong")
}
}
- 承诺版
function getData() {
return new Promise((resolve, reject) => {
fetch(url)
.then(res => res.json())
.then(data => resolve(data))
.catch(error => reject(error));
});
}
const callGetData = () => {
getData()
.then(data => console.log(data))
.catch(error => console.log("Something gone wrong"));
}
最后:
callGetData();
两个 sn-ps 似乎都可以工作。写 async / await 版本对我来说更容易。
问题:
- 在这种情况下我可以正确使用 Promise 吗?
- 是否有一些可能的改进?
感谢您的帮助。
【问题讨论】:
标签: node.js promise async-await fetch