axios 在JavaScript中,如何从一个函数返回一个变量,而该函数从另一个函数获取变量?

kwvwclae  于 2022-12-04  发布在  iOS
关注(0)|答案(2)|浏览(253)

我有多个函数,可以将数据从一个函数传递到另一个函数。我将其中一个函数移到后端,并使用Axios作为API接收数据。现在我无法将Axios中的数据分配给某个局部变量。简单的代码如下:

function function1()
 {
   axios({get, url})
  .then(response => {
   globalVariable = response.data;
   function2(globalVariable);
 }

function function2(globalVariable)
  {
   const local = globalVariable;
   return local;
  }

在函数3中,我想做:

function function3() 
 { 
  const from_local = function2()
  from_local
 }

当我尝试这个我收到undefined结果。请帮助。

b91juud3

b91juud31#

看起来你正在寻找某种管道异步操作。我所说的管道是指一个函数执行的结果将被馈送到另一个函数。
基本上,function1模拟了axios操作。

// making an api call
function function1() {
  return fetch('https://jsonplaceholder.typicode.com/todos/1').then((d) =>
    d.json()
  );
}
// some random function
function function2(data) {
  console.log(' Calling function 2 ');
  return data?.title;
}
// some random function
function function3(data) {
  console.log(' Calling function 3 ');
  return `Hello ${data}`;
}
/** a function to resolve functions sequentially. The result of first 
   function will be input to another function. 
   Here ...fns is creating an array like object 
   so array operations can be performed here **/

const runAsynFunctions = (...fns) => {
  return (args) => {
    return fns.reduce((acc, curr) => {
      return acc.then(curr);
    }, Promise.resolve(args)); 
  };
};
// calling runAsynFunctions with and passing list of 
// functions which need to resolved sequentially 

const doOperation = runAsynFunctions(function2, function3);

// resolving the api call first and the passing the result to 
// other functions

function1().then(async(response) => {
  const res = await doOperation(response);
  console.log(res);
});
7fyelxc5

7fyelxc52#

这就是承诺的意义所在。不需要全局变量或跳过重重障碍来获取数据。只要记住await任何异步函数(如axios),并将任何包含“await”的函数注解为async即可。

// note "async" because it contains await
async function backend() {
  // note await because axios is async
  const response = await axios({get, url});
  return response.data;
}

// same thing up the calling chain
async function middleend() {
  const local = await backend();
  return local;
}

async function frontend() {
  const local = await middleend();
  console.log('ta da! here\'s the data', local);
}

相关问题