前端异步请求async/await,axios的错误用法

request为包装后的axios请求
1、直接return请求,得到promise,获取不到返回值,

 const tmp = async () => {
    return request({
      method: "post",
      url: "/auth/login",
      data: {
        username: name,
        password: pw,
      },
    });
    console.log("login request", tmp);

2、post请求使用params传递参数

const LoginApi = async (name: string, pw: string) => {
  const tmp = await request({
    method: "post",
    url: "/auth/login",
    params: {
      username: name,
      password: pw,
    },
  });
  console.log("login request", tmp);
};

3、没执行async函数

const LoginApi = (name: string, pw: string) => {
  async () => {
    const tmp = await request({
      method: "post",
      url: "/auth/login",
      data: {
        username: name,
        password: pw,
      },
    });
    console.log("login request", tmp);
  };
};
async () => {
        const res = await fetch(uri, { method: "GET" });
        const resText = await res.text();
        console.log("request:", resText);
      };

4、正确写法

const iGet= async () => {
        const res = await fetch(uri, { method: "GET" });
        const resText = await res.text();
        console.log("request:", resText);
      };
iGet()

你可能感兴趣的:(前端,前端,javascript,开发语言)