首页 > 解决方案 > Javascript:使用 Promise 链接 axios 调用

问题描述

我的项目中有 3 个使用 axios 的调用:

  1. 获取访问令牌
  2. 获取车辆品牌,然后过滤并返回正确的 makeId(使用令牌)
  3. 获取车辆模型,然后过滤并返回正确的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);
  });
}

标签: javascriptpromiseaxioses6-promise

解决方案


推荐阅读