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 result;


this.$publicUtils.codeFilters("10", "GGZT").then(res => {

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

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

A good man is safe all his life~

4 Replies
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");

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");
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

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