【问题标题】:replicating fetch with promises and xhr - JavaScript使用 Promise 和 xhr 复制 fetch - JavaScript
【发布时间】: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


【解决方案1】:

你把 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));

【讨论】:

  • 不,也不要在那里使用它 - 避免使用 Promise constructor antipattern!
  • 我已尝试根据您的建议更改我的代码,但 then() jsfiddle.net/k8oywhbn987654322@ 出现错误
  • 删除.then(data => data.json()) 并返回_fetch()(更新答案)
猜你喜欢
  • 2022-06-17
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 2017-06-11
  • 2016-04-13
  • 2022-11-14
相关资源
最近更新 更多