Javascript:使用承诺链接axios调用
在我的项目中,我有3个与axios的通话:Javascript:使用承诺链接axios调用,javascript,promise,axios,es6-promise,Javascript,Promise,Axios,Es6 Promise,在我的项目中,我有3个与axios的通话: 获取访问令牌 获取车辆品牌,然后过滤并返回正确的品牌ID(使用令牌) 获取车辆模型,然后过滤并返回正确的模型ID(使用makeId和令牌) 目标是使用一系列承诺(我正试图弄清楚),首先调用令牌并将其设置为变量,然后调用并返回makeId,然后调用并返回modelId 每个axios调用都是成功的,我能够筛选到正确的值,但我不知道如何将值返回到链中的下一步,或者如何准确地链接每个调用 我试过这样的方法: const getToken = () =
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()中添加新的承诺,还是有办法将它们链接到多个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
});
}
感谢您在理解承诺和链接方面给予的帮助
更新:
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);
});
}
getToken()
不返回任何内容。它必须是return axios(config).
,在这个问题上起到了很好的作用。非常感谢。现在要继续这个链,我是否要在第一个的then()中添加一个新的承诺?当您从then()
返回时,它已经包装在一个承诺中,无需创建另一个getToken()。然后(…)
,并且一旦您进入。然后()
chains只需记住在下一部分的末尾返回值即可。这太复杂了。正如andy所说,您不需要做出新的承诺,只需getToken.then(res=>{token=res;return getMakes(year,make,token);})代码>(假设getMakes()
返回一些内容)。同样,您总是需要从then块返回一些内容,否则下一步将一无所获。