javascript - Javascript:使用 Promise 链接 axios 调用
问题描述
我的项目中有 3 个使用 axios 的调用:
- 获取访问令牌
- 获取车辆品牌,然后过滤并返回正确的 makeId(使用令牌)
- 获取车辆模型,然后过滤并返回正确的modelId(使用makeId和token)
目标是使用 Promises 链(我正在尝试弄清楚)首先调用令牌并将其设置为变量,然后调用并返回 makeId,然后调用并返回 modelId
每个 axios 调用都是成功的,我能够过滤到正确的值,但我不知道如何将值返回到链中的下一步或如何准确地链接每个调用。
我试过类似的东西:
const getToken = () => {
var data = JSON.stringify({"accessType":"user","credentials":{"user":{"id":"my_account","key":"123456789"}}});
var config = {
method: 'post',
url: 'https://api.myapi.com/token/access',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then( res => {
return res.data.token;
})
.catch(e=> {
console.error(e.message);
});
}
const getInfo = (year,make,model) => {
new Promise((resolve,reject) => {
resolve(getToken())
})
.then( token => {
console.log(token); //Where I thought I could see the return of the axios call in it's
then() which would be the token
});
}
getInfo(2012,'Kia',;'Rio');
此外,在返回令牌后,我需要使用 getMakes() 和 getModels() 执行相同的过程,将响应值添加到下一个函数。我会在每个 then() 中添加新的 Promises,还是有办法将它们链接在多个 then() 下并将我的返回值存储在函数的块范围内?
const getInfo = (year,make,model) => {
let token;
let makeId;
let modelId;
new Promise((resolve,reject) => {
resolve(getToken())
})
.then( result => {
token = result;
//then I need to call getModel(year,make,token) and wait for it's response
});
}
感谢您在理解 Promise 和链接方面提供的任何帮助!
更新:
export const getInfo = (year,make,model) => {
let token;
new Promise((resolve,reject) => {
resolve(getToken());
})
.then( res => {
token = res;
getMakes(year,make,token);
})
.then(res => {
console.log(res);
});
}
解决方案
推荐阅读
- r - 如何在ggplot上注释行?
- java - Android WebView 代理设置
- file-upload - CloudFlare - 413 请求实体太大
- php - 视图值更改后如何更新 MySQL 数据库
- android - 在使用 Kotlin 的 Android 中需要帮助
- css - ionic 3 内容背景不起作用
- c++ - Problem assigning a value to an "adjacent" variable
- regex - Notepad++ 正则表达式屏蔽/清理数据
- html -
- 在没有换行的情况下不显示在 ie 8 中
- 在没有换行的情况下不显示在 ie 8 中
- c# - 在代码隐藏中设置属性的按钮不触发点击事件