技术解析

关于 fetch 的一个问题
0
2021-08-11 04:44:41
idczone

为什么第二种写法会报错:

fetch('xxx').then(res => res.json());  //ok

fetch('xxx').then(Response.prototype.json.call);  //TypeError: undefined is not a function

如果把 fetch 返回的 Stream 对象打印出来,用 Store as global variable 保存到变量 temp1 是可以正常使用 Response.prototype.json.call 的:

Response.prototype.json.call(temp1).then(console.log);  //ok

var a = Response.prototype.json.call
console.log(a) // undefined
这样懂么

变量 a 打印出来是 ƒ call() { [native code] } ,undefined 是 console.log 的返回值

你调用一下 a 就知道了。

原来如此,需要给 call 绑定 this,这样就没问题了:fetch('xxx').then(Function.call.bind(Response.prototype.json))

这是可以继续执行 fetch 返回的函数吗?

没明白你问的是什么,fetch 返回的是 Promise,Promise 中 resolve 的值为 fetch 获取的流对象,then 接收一个回调函数作为参数,回调函数接收到的参数即为 resolve 的流对象,可以使用这个回调函数来处理流对象

我是想问如果 resolve 后的 object 包含一个函数体,Function call 会执行这个函数吗? XSS 那种。

不会。这种写法等价于 (res) => res.xxx() ,只是把流对象解析成 xxx 格式而已,要执行函数的话使用 jsonp 才行吧。

嗯,明白了,谢谢

数据地带为您的网站提供全球顶级IDC资源
在线咨询
专属客服