【发布时间】:2019-07-23 18:58:47
【问题描述】:
我想创建自己的 fetch 函数来更好地理解 XMLHttpRequest、Promises 和 Async/Await。
当我在 then() 中遇到错误时,它似乎没有返回一个承诺
const fakeFetch = url => {
const xhr = () => new Promise((resolve, reject) => {
try {
const x = new XMLHttpRequest();
x.onreadystatechange = function() {
const { readyState, status } = this;
if (readyState === 4 && status === 200) {
resolve(x.responseText);
}
}
x.open('get', url);
x.send();
} catch(e) {
reject(e);
}
})
const _fetch = () => new Promise(async (resolve, reject) => {
try {
const response = await xhr();
if (response !== undefined) resolve(response);
} catch(e) {
reject(e);
}
})
_fetch();
}
fakeFetch('https://api.github.com/users')
.then(data => data.json())
.then(data => console.log(data));
【问题讨论】:
-
错误似乎很明显:你不能使用
await,除非它在async函数中。 -
我已经修复了它仍然返回 undefined
-
要更好地理解 async/await,您需要了解您 shall not use it here at all! :-D
-
@Bergi,我很欣赏这个建议,但我试图理解更大的图景,只是试图理解为什么整体代码不能正常工作。这不是我在生产中使用的东西。
-
当然不是(你会使用标准的 polyfill),但你仍然不应该将
async function传递给new Promise,甚至不应该摆弄。
标签: javascript