简体   繁体   English

从另一个 function javascript 调用异步 function 时变得未定义

[英]Getting undefined when calling an async function from another function javascript

For this project I am using wretch, which is a wrapper around fetch对于这个项目,我使用的是 wretch,它是 fetch 的包装器

This is a breakout of my code:这是我的代码的一个突破:

I have the wretch calls on a seperate service file to separate the render functionality from the wretch functionality.我对单独的服务文件进行了可怜的调用,以将渲染功能与可怜的功能分开。

I am exporting我要出口

export const wretchFunc = var => {
  return wretch(url)
    .json({
      var,
    })
    .get()
    .json()
};

The problem is with the second file: The function2 renders the result of the wretch function, I do resolve the promise and I get the result that I want but when I call it from function1 the return value is undefined even-though placing a console.log inside function2 gives me the boolean that I am looking for.问题出在第二个文件上:函数 2 呈现了这个可怜的 function 的结果,我确实解决了 promise 并且我得到了我想要的结果,但是当我从函数 1 调用它时,即使放置了一个控制台,返回值也是未定义的。在 function2 中登录给了我正在寻找的 boolean。

I have a function1 that returns:我有一个 function1 返回:

return (function2 || function3)

and the function2 renders the result of wretchFunc and something like this:并且 function2 呈现 wretchFunc 的结果,如下所示:

function function2(state) {
  const var = fun(state);
  if (!var) {
    return false;
  }
  wretchFunc(var).then(json => {
    return JSON.parse(json).isTrue;
  });
}

My assumption is that function one gets executed before receiving the result of the function2 but I am not sure what to do.我的假设是 function 在收到 function2 的结果之前执行,但我不知道该怎么做。

Edit: I tried doing:编辑:我试着做:

 return wretchFunc(var).then(json => {
    return JSON.parse(json).isTrue;
  });
}

Which gives me another promise that I can resolve on the upper function, but since I have a previous condition if(.var) that returns false that would make the function return 2 different things.这给了我另一个 promise,我可以在上面的 function 上解决它,但是由于我有一个先前的条件 if(.var) 返回 false,这会使 function 返回不同的东西。 is there a way that I can cast the value of the promise in function2 and force function1 to wait for its result.有没有一种方法可以将 promise 的值转换为 function2 并强制 function1 等待其结果。

Thanks谢谢

Try wrapping into new Promise and returning it尝试包装成新的 Promise 并返回它

function function2(state) {
  return new Promise((res, rej) => {
    const var = fun(state);
    if (!var)
      res(false);
    wretchFunc(var)
    .then(json => resolve(JSON.parse(json).isTrue)
    .catch(err) => rej(err));
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM