【问题标题】:How to get data from Promise function如何从 Promise 函数中获取数据
【发布时间】:2021-10-09 23:52:37
【问题描述】:

我有一个问题,不知道为什么我不能从另一个文件的函数中获取返回数据,我在这里尝试

我的文件.js

const psm = require("../services/psm");
psm.show(12).then((res) => console.log(res));

我的服务.js

const axios = require("../plugins/axios").default;
const module = "psm";

exports.show = async (payload) => {
  await axios
    .get(`/${module}/${payload}`)
    .then((res) => {
      return res.data.data;
    })
    .catch((err) => {
      return Promise.reject(err.response);
    })
    .finally(() => {});
};

我得到undefined 返回..

【问题讨论】:

  • show 不返回任何内容。
  • 你能解释更多吗,我不是专家..
  • async..await 是 Promise 的语法糖。这里用错了。尽管它很有帮助,但我建议在您了解它的确切作用之前不要使用它。您将它们一起使用表明它是无缘无故的意外使用。

标签: javascript vue.js promise


【解决方案1】:

代码中的问题:

  • show 函数没有显式返回任何东西;因此,show 函数返回的承诺以 undefined 的值实现

可以对您的代码进行的改进:

  1. catchfinally 块是不需要的; catch 块是不必要的,因为由于 catch 块而返回的拒绝承诺将需要由调用 show 函数的代码处理。

    无论如何,您都需要catch 方法或阻塞调用代码。因此,只需删除 catch 块并允许调用代码捕获并处理错误

  2. show 函数不需要是async。您可以只返回axios.getaxios.get(...).then(...) 的结果

“show”方法的最终版本:

exports.show = (payload) => {
  return axios
    .get(`/${module}/${payload}`)
    .then((res) => {
      return res.data.data;
    });
}

您可以将此函数称为:

psm.show(12)
   .then(res => console.log(res))
   .catch(error => { /* handle the error */ });

show 函数的替代版本:

exports.show = (payload) => {
  return axios.get(`/${module}/${payload}`);
}

您可以将此版本的show 函数调用为:

psm.show(12)
   .then(res => console.log(res.data.data))
   .catch(error => { /* handle the error */ });

【讨论】:

  • "show function doesn't need to be async" - 没有 async 函数 needs 必须是 async,所有这些都可以用原始 Promise 编写。这并不意味着它们不应该被使用。
  • @EstusFlask 我认为您误解了我的意思。当然,每个async 函数都可以使用原始承诺编写,但我特别指的是show 函数。查看此函数的代码,很明显它是不必要的async,因为它没有利用async-await 语法提供的简洁语法。更不用说由 async show 函数创建的 promise 对 axios.get 创建的 promise 进行不必要的包装。
  • 我同意在这种情况下使用return 修复它比将整个函数重写为正确的 async..await 更容易
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
相关资源
最近更新 更多