【发布时间】:2020-05-24 18:23:59
【问题描述】:
我的 2 个 API 调用恰好同时发生,其中 API1 的响应将作为请求参数发送到 API2。但是,该值未定义,因为直到那时才获取它。有什么办法可以在反应中解决。
【问题讨论】:
标签: javascript reactjs async-await axios mobx
我的 2 个 API 调用恰好同时发生,其中 API1 的响应将作为请求参数发送到 API2。但是,该值未定义,因为直到那时才获取它。有什么办法可以在反应中解决。
【问题讨论】:
标签: javascript reactjs async-await axios mobx
有多种方法可以解决这个问题,我将解释一种最新的也是最受追捧的解决问题的方法。
我相信您一定听说过 JavaScript 中的 async/await,如果您还没有听说过,我建议您阅读有关该主题的 MDN 文档。
这里有2个关键字,async && await,我们一个一个来看看。
异步
在任何函数之前添加异步意味着一件简单的事情,而不是返回正常值,现在函数将返回 Promise
例如,
async function fetchData() {
return ('some data from fetch call')
}
如果您只是通过 fetchData() 在控制台中运行上述函数。您会看到,这个函数没有返回字符串值,而是返回了一个 Promise。
简而言之,async 确保函数返回一个承诺,并将非承诺包装在其中。
等待
我相信现在你已经猜到了我们为什么除了 async 之外还使用关键字 await,仅仅是因为关键字 await em> 让 JavaScript 等到该承诺(由异步函数返回)完成并返回其结果。
现在开始讨论如何使用它来解决您的问题,请按照以下代码 sn-p。
async function getUserData(){
//make first request
let response = await fetch('/api/user.json');
let user = await response.json();
//using data from first request make second request/call
let gitResponse = await fetch(`https://api.github.com/users/${user.name}`)
let githubUser = await gitResponse.json()
// show the avatar
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
// wait 3 seconds
await new Promise((resolve, reject) => setTimeout(resolve, 3000));
img.remove();
return githubUser;
}
如您所见,上面的代码非常容易阅读和理解。另请参阅THIS 文档以获取有关 JavaScript 中 async/await 关键字的更多信息。
【讨论】:
Asyn/await 解决了你的问题:
const requests = async () =>{
const response1 = await fetch("api1")
const result1 = await response1.json()
// Now you have result from api1 you might use it for body of api2 for exmaple
const response2 = await fetch("api2", {method: "POST", body: result1})
const result2 = await response1.json()
}
【讨论】:
如果您使用 react hooks,您可以使用 Promise 将您的 API 调用链接到 useEffect
useEffect(() => {
fetchAPI1().then(fetchAPI2)
}, [])
【讨论】:
fetch(api1_url).then(response => {
fetch(api2_url, {
method: "POST",
body: response
})
.then(response2 => {
console.log(response2)
})
})
})
.catch(function (error) {
console.log(error)
});
或者如果使用 axios
axios.post(api1_url, {
paramName: 'paramValue'
})
.then(response1 => {
axios.post(api12_url, {
paramName: response1.value
})
.then(response2 => {
console.log(response2)
})
})
.catch(function (error) {
console.log(error);
});
【讨论】: