【问题标题】:How do I access the return of an axios function? Or should I be using callback?如何访问 axios 函数的返回值?还是我应该使用回调?
【发布时间】:2019-08-18 10:59:46
【问题描述】:

获取一些记录并发出 POST 命令发送出去,我能够在日志中看到正确的记录 ID,因此逻辑工作。只是不知道如何检索这些值,我尝试过 async/await 并获得未解决的承诺响应并按原样运行返回未定义。异步新手,非常感谢任何帮助!

const axios = require('axios');
  exports.handler = (event, context, callback) => {

    async function getJobId() { 
      var jobId
      axios({
          method: 'get',
          headers: {'<Api-Key>': '<my-api-key-value>'},
          url: 'https://api.my-website.com/v1/jobs',
          params: { jobNumber: event.jobNumber }
        })
        .then((res) => {
          var i,j,x;
          for (i in res.data) {
            for (j in res.data[i]){
              x = res.data[i][j];
              jobId = x.id;
            }
          }
          console.log('jobId:',jobId);
          return jobId;
        })
        .catch(function (error) {
          console.log('getJobIdError');
          console.log(error);
        });
    }

    function getMaterialId() { 
        var materialId;
        axios({
          method: 'get',
          headers: {'<Api-Key>': '<my-api-key-value>'},
          url: 'https://api.my-website.com/v1/materials',
        })
        .then((res) => {
          var i,j,x;
          for (i in res.data) {
            for (j in res.data[i]){
              x = res.data[i][j];
              if(x.primaryVendor.vendorPart == event.material){
                materialId = x.id;
              }
            }
          }
          console.log('materialId:',materialId);
          return materialId;
        })
        .catch(function (error) {
          console.log('getMaterialIdError');
          console.log(error);
        });
    }

    function getTechId() { 
        var techId;
        axios({
          method: 'get',
          headers: {'<Api-Key>': '<my-api-key-value>'},
          url: 'https://api.my-website.com/v1/technicians',
        })
        .then((res) => {
          var i,j,x;
          var fn = event.firstName;
          var ln = event.lastName;
          var fullName = fn.trim() + ' ' + ln.trim();
          for (i in res.data) {
            for (j in res.data[i]){
              x = res.data[i][j];
              if(x.name == fullName){
                techId = x.id;
              }
            }
          }
          console.log('techId:', techId);
          return techId;
        })
        .catch(function (error) {
          console.log('getTechId');
          console.log(error);
        });
    }

    function allIds() {
      axios.all([
        getMaterialId(),
        getJobId(),
        getTechId()
      ]);
    }
    allIds();
 };

在输出日志中,我得到了正确的记录 ID:

回应: 空

请求 ID:"50972993-4971-4dcc-b577-0f253f3f3571" 功能日志:

START RequestId:50972993-4971-4dcc-b577-0f253f3f3571 版本:$LATEST 2019-08-17T21:51:51.192Z 50972993-4971-4dcc-b577-0f253f3f3571 技术 ID:1025 2019-08-17T21:51:51.233Z 50972993-4971-4dcc-b577-0f253f3f3571 材料 ID:1725 2019-08-17T21:51:51.432Z 50972993-4971-4dcc-b577-0f253f3f3571 jobId: 37399080 结束请求 ID:50972993-4971-4dcc-b577-0f253f3f3571 报告请求 ID:50972993-4971-4dcc-b577-0f253f3f3571 持续时间:1148.69 毫秒计费持续时间:1200 毫秒内存大小:128 MB 使用的最大内存:65 MB

【问题讨论】:

  • 不能从回调中返回值。请改用回调。
  • 那么它只返回三个中的第一个。

标签: asynchronous axios


【解决方案1】:

我明白了,Rohit Kashyap 为我指明了正确的方向,谢谢 Rohit。我试图避免嵌套的 axios,因为我读到它会变得很粘,但在这里似乎工作得很好。它可以满足我的需要,但对异步很陌生,所以如果有人看到问题,请告诉我。

const axios = require('axios');
  exports.handler = (event, context, callback) => {

      var jobId;
      var materialId;
      var techId;

      axios.all([ 

        axios({
          method: 'get',
          headers: {'<Api-Key>': '<my-api-key>5'},
          url: 'https://api.my-website.com/v1/jobs',
          params: { jobNumber: event.jobNumber }
        })
        .then((res) => {
          var i,j,x;
          for (i in res.data) {
            for (j in res.data[i]){
              x = res.data[i][j];
              jobId = x.id;
            }
          }
          console.log('jobId:',jobId);
        })
        .catch(function (error) {
          console.log('getJobIdError');
          console.log(error);
        }),

        axios({
          method: 'get',
          headers: {'<Api-Key>': '<my-api-key>5'},
          url: 'https://api.my-website.com/v1/materials',
        })
        .then((res) => {
          var i,j,x;
          for (i in res.data) {
            for (j in res.data[i]){
              x = res.data[i][j];
              if(x.primaryVendor.vendorPart == event.material){
                materialId = x.id;
              }
            }
          }
          console.log('materialId:',materialId);
        })
        .catch(function (error) {
          console.log('getMaterialIdError');
          console.log(error);
        }),

        axios({
          method: 'get',
          headers: {'<Api-Key>': '<my-api-key>5'},
          url: 'https://api.my-website.com/v1/technicians',
        })
        .then((res) => {
          var i,j,x;
          var fn = event.firstName;
          var ln = event.lastName;
          var fullName = fn.trim() + ' ' + ln.trim();
          for (i in res.data) {
            for (j in res.data[i]){
              x = res.data[i][j];
              if(x.name == fullName){
                techId = x.id;
              }
            }
          }
          console.log('techId:', techId);
        })

        .catch(function (error) {
          console.log('getTechIdError');
          console.log(error);
        })
      ])
      .then((res) => {
        callback( null, {
            jobId,
            materialId,
            techId,
        });
      })
      .catch(function (error) {
          console.log('getAllIdError');
          console.log(error);
      });
  };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    相关资源
    最近更新 更多