Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
理解Fetch()Javascript_Javascript_Promise_Fetch Api - Fatal编程技术网

理解Fetch()Javascript

理解Fetch()Javascript,javascript,promise,fetch-api,Javascript,Promise,Fetch Api,我正在学习javascript教程,需要一些帮助来理解以下函数中的模式: get: function(url) { return fetch(rootUrl + url, { headers: { 'Authorization': 'Client-ID ' + apiKey } } ) .then( function(response) {

我正在学习javascript教程,需要一些帮助来理解以下函数中的模式:

get:  function(url) {
         return fetch(rootUrl + url, {
            headers: {
                'Authorization': 'Client-ID ' + apiKey
            }
        } )
        .then(
            function(response) {
                return response.json();
            }
        );
    }

我感到困惑的是,如果我们只关心response.json(),那么返回fetch()有什么意义呢?

返回
获取
链接
的能力。然后()
.catch()
.get()
调用,例如

obj.get(url).then(function(data) {
  console.log(data)
})
没有
return
语句
obj.get(url)。那么(handler)
可能会记录错误,如果对象没有名为
的属性,那么
其中value是一个函数,它处理从
fetch
返回的
Promise
,其中没有从
get
函数返回的值

var objWithReturn={
获取:函数(url){
返回承诺。解析(url)
.那么(
功能(响应){
返回JSON.parse(response);
}
);
}
}
objWithReturn.get(“{”a“:1}”)
.then(功能(数据){
console.log(数据)

})
它不会返回
fetch()
。编写链接函数调用时,如:

return f1(args).f2(otherargs);
这相当于:

var temp1 = f1(args);
var temp2 = temp1.f2(otherargs);
return temp2;
因此,您的函数可以写成:

get: function(url) {
    var promise1 = fetch(rootUrl + url, {
        headers: {
            'Authorization': 'Client-ID ' + apiKey
        }
    });
    var promise2 = promise1.then(function(response) {
        return response.json();
    });
    return promise2;
}

现在您可以看到,它返回了一个承诺,即当它已满时,将从响应返回JSON。

第二个示例中有一个输入错误。应该是:
objWithoutReturn