gpt4 book ai didi

javascript - 使用 Promise 和 xhr 复制 fetch - JavaScript

转载 作者:行者123 更新时间:2023-12-01 01:13:39 26 4
gpt4 key购买 nike

我想创建自己的获取函数来更好地理解 XMLHttpRequest、Promises 和 Async/Await。

它似乎没有返回 promise ,因为我在 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));

最佳答案

您将 async 关键字放在了错误的位置,它应该在这里:

let p = new Promise(async (resolve, reject) => {
^^^^^

await 函数,它必须返回一个 Promise :(但在这个用例中,您实际上不需要 await )

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((resolve, reject) => {
try {
const response = xhr();
if (response !== undefined) resolve(response);
} catch (e) {
reject(e);
}
})

return _fetch();
}

fakeFetch('https://api.github.com/users')
.then(data => console.log(data));

关于javascript - 使用 Promise 和 xhr 复制 fetch - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54949788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com