简体   繁体   English

使用 promises 和 xhr 复制 fetch - JavaScript

[英]replicating fetch with promises and xhr - JavaScript

I want to create my own fetch function to understand better XMLHttpRequest, Promises and Async/Await.我想创建我自己的 fetch 函数来更好地理解 XMLHttpRequest、Promises 和 Async/Await。

It doesn't seem like it's returning a promise as I get errors with then()当我遇到 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));

you're putting the async key word in the wrong place, it should be here : 您将async关键字放在错误的位置,应该在这里:

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

And to await for a function, it has to return a Promise : ( But in this use case you don't really need to await ) 为了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)); 

您只需要返回_fetch()而不是仅仅执行它,并且由于XMLHttpRequest返回的是responseText,那么您无需在then中解析json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM