gpt4 book ai didi

javascript - 在 javascript 中使用另一个 fetch 中的 fetch

转载 作者:行者123 更新时间:2023-12-02 23:06:02 26 4
gpt4 key购买 nike

我想要获取一个 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)
});

最佳答案

Fetch 返回一个 promise ,你可以 chain multiple promises ,并在第二个请求中使用第一个请求的结果,依此类推。

此示例使用 SpaceX API获取最新发射的信息,找到火箭的id,并获取火箭的信息。

const url = 'https://api.spacexdata.com/v4';

const result = fetch(`${url}/launches/latest`, { method: 'get' })
.then(response => response.json()) // pass the data as promise to next then block
.then(data => {
const rocketId = data.rocket;

console.log(rocketId, '\n');

return fetch(`${url}/rockets/${rocketId}`); // make a 2nd request and return a promise
})
.then(response => response.json())
.catch(err => {
console.error('Request failed', err)
})

// I'm using the result const to show that you can continue to extend the chain from the returned promise
result.then(r => {
console.log(r.first_stage); // 2nd request result first_stage property
});
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 在 javascript 中使用另一个 fetch 中的 fetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40981040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com