undefinedfix
Sign in

How to call the method defined by async to directly return a value defined by yourself instead of a promise object

mbevj edited in Fri, 18 Nov 2022
The async method is defined as follows
 /**
 * @description 根据值集代码获取值集名称
 * @param { String } code 值集代码
 * @param { String } codeType 值集类型
 * @return { String } 值集名称
 */
 async codeFilters(code, codeType) {

   let result = "";
   
   //这里进行了一次异步请求的操作,把拿到的数据进行筛选过滤得到自己想要的东西
   await this.getCodeData(codeType).then( data => {
     let res = data.find(item => {
       return item.itemCode == code;
     });
     result = (res ? res.itemName : "");
   });
   
   //在这里return出去
   return result;
 },

Description:


//现调用情况:调用后会返回一个Promise对象,只有在then里才能拿到返回的数据
//例:
this.$publicUtils.codeFilters("10", "GGZT").then(res => {
   console.log(res);
});

//现希望返回值不是Promise对象, 直接是我return回来的值。方便我去使用 
let res = this.$publicUtils.codeFilters("10", "GGZT");
console.log(res)

//这样的话我可以 把方法直接丢结构里去渲染 
//例:{{ $publicUtils.codeFilters("10", "GGZT") }}

A good man is safe all his life~

4 Replies
Tohiko
commented on Fri, 18 Nov 2022

This can't be saved. It's asynchronous code, either then or await promise. If you don't like then, use await (of course, add async before the function that contains the following sentence of code)

let res = await this.$publicUtils.codeFilters("10", "GGZT");

console.log(res)
aleonjhon
commented on Sat, 19 Nov 2022

The return value of aync must be promise

But you can get the value directly with await

let res = await this.$publicUtils.codeFilters("10", "GGZT");
hlvlr
commented on Sat, 19 Nov 2022

Then () is used to return the data successfully thrown by the promise object. Await is used to wait for the promise object to throw data. It can only be used in async functions. So this$ publicUtils.codeFilters ("10", "ggzt") itself is a promise object. You can put it directly in async function and

console.log(await this.$publicUtils.codeFilters("10", "GGZT"))

that will do

Scarecrow
commented on Sat, 19 Nov 2022

Once async is used, it is already an asynchronous operation. It is impossible to use async as synchronous operation. Why use await