Mon*_*a92 29 javascript fetch-api
我想得到一个api,然后再打电话给另一个.在javascript中明智地使用这样的代码吗?
fetch(url, {
method: 'get',
}).then(function(response) {
response.json().then(function(data) {
fetch(anotherUrl).then(function(response) {
return response.json();
}).catch(function() {
console.log("Booo");
});
});
})
.catch(function(error) {
console.log('Request failed', error)
});
Run Code Online (Sandbox Code Playgroud)
Ori*_*ori 47
Fetch返回一个promise,你可以链接多个promise,并在第二个请求中使用第一个请求的结果:
该示例使用SpaceX API获取最新发射的信息,找到火箭的id,并获取火箭的信息.
var url = 'https://api.spacexdata.com/v2/launches/latest';
var result = fetch(url, {
method: 'get',
}).then(function(response) {
return response.json(); // pass the data as promise to next then block
}).then(function(data) {
var rocketId = data.rocket.rocket_id;
console.log(rocketId, '\n');
return fetch('https://api.spacexdata.com/v2/rockets/' + rocketId); // make a 2nd request and return a promise
})
.then(function(response) {
return response.json();
})
.catch(function(error) {
console.log('Request failed', error)
})
// I'm using the result variable to show that you can continue to extend the chain from the returned promise
result.then(function(r) {
console.log(r); // 2nd request result
});
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)
gue*_*314 15
嵌套fetch()
调用没有问题.这取决于您通过嵌套调用尝试实现的目标.
您也可以使用.then()
链接来电.另请参见如何构造嵌套的Promises
fetch(url)
.then(function(response) {
return response.json()
})
.then(function(data) {
// do stuff with `data`, call second `fetch`
return fetch(data.anotherUrl)
})
.then(function(response) {
return response.json();
})
.then(function(data) {
// do stuff with `data`
})
.catch(function(error) {
console.log('Requestfailed', error)
});
Run Code Online (Sandbox Code Playgroud)
这是人们在开始使用 Promises 时被绊倒的一个常见问题,包括我自己。不过,首先...
很高兴您尝试使用新的Fetch API,但如果我是您,我现在会使用 XMLHttpRequest 实现,例如 jQuery AJAX 或 Backbone 的 jQuery 的覆盖实现.ajax()
,如果您已经在使用这些库。原因是 Fetch API 还很新,因此在这个阶段是实验性的。
话虽如此,人们肯定会使用它,但我不会在我自己的生产代码中使用它,直到它脱离“实验”状态。
如果您决定继续使用fetch
,则可以使用polyfill。注意:您必须跳过额外的环节才能使错误处理正常工作,并从服务器接收 cookie。如果您已经在加载 jQuery 或使用 Backbone,那么现在就坚持使用它们;无论如何,并不完全可怕。
你想要一个扁平的结构,否则你就错过了 Promises 的重点。嵌套 Promise 是不明智的,因为 Promise 解决了嵌套异步回调(回调地狱)无法解决的问题。
只需使用更具可读性的代码结构,您就可以节省自己的时间和精力,并减少错误代码的产生。这不是全部,但它是游戏的一部分,可以这么说。
Promises 是关于让异步代码保留同步代码的大部分丢失属性,例如平面缩进和一个异常通道。
-- Petka Antonov(蓝鸟承诺图书馆)
// run async #1
asyncGetFn()
// first 'then' - execute more async code as an arg, or just accept results
// and do some other ops
.then(response => {
// ...operate on response data...or pass data onto next promise, if needed
})
// run async #2
.then(asyncGetAnotherFn)
.then(response => {
// ...operate on response data...or pass data onto next promise, if needed
})
// flat promise chain, followed by 'catch'
// this is sexy error handling for every 'then' above
.catch(err => {
console.error('Request failed', err)
// ...raise exeption...
// ... or, retry promise...
})
Run Code Online (Sandbox Code Playgroud)