使用promise和xhr复制抓取-JavaScript

时间:2019-03-01 17:44:36

标签: javascript

我想创建自己的提取函数以更好地理解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));

2 个答案:

答案 0 :(得分:2)

您将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));

答案 1 :(得分:1)

您只需要返回_fetch()而不是仅仅执行它,并且由于XMLHttpRequest返回的是responseText,因此您无需在当时解析json