undefinedfix
Sign in

Is it possible to optimize the combination of promise and async in ES6

21CCCS edited in Thu, 26 Jan 2023

Is it possible to optimize using await inside promise objects

// a.js

const PublicClass = {
    list: async () => {
        ... // 此处业务逻辑等待时间比较长,但最终会有一个返回结果
    }
}
module.exports = {
    test: async () => {
        // 此处在promise的回调函数加上async是否可优化
        return new Promise(async(resolve, reject) => {
            cosnt res = await PublicClass.list()
            resolve(res)
        })
    }
}

The above writing method can achieve the expected results. Now I would like to ask if there is an optimized writing method.
Business requirements PublicClass.list It must have async. If it is written directly in the following way, it will not achieve the expected effect
   // a.js

const PublicClass = {
    list: async () => {
        ... // 此处业务逻辑等待时间比较长,但最终会有一个返回结果
    }
}
module.exports = {
    test: async () => {
        cost res = await PublicClass.list()
        return res
    }
} 


Now I am using Google's puppeter. The specific code is as follows:

    // 这是文档给的例子
   
   const puppeteer = require('puppeteer');  
   puppeteer.launch().then(async browser => {  
   const page = await browser.newPage();  
   await page.goto('https://baidu.com');  
    await browser.close();
  });
  
  
 const puppeteer = require('puppeteer'); 

 const PublicClass = {
   list: async () => {
    try {
        const browser = await puppeteer.launch()
        const page = await browser.newPage();  
        await page.goto('https://baidu.com');  
        await browser.close();
    } catch (err) {
        console.log(err)
    }
  }
// 
module.exports = {
    test: async () => {
        return new Promise(async (resolve, reject) => {
            cosnt res = await PublicClass.list()
             resolve(res)
        })
    }
} 

If you don't use async in the callback of promise, is there a better way to write it

1 Replies
ravindu
commented on Thu, 26 Jan 2023

Why not return a promise in the list?

---------Split line: I'll supplement the use of async / await

Async / await is just the syntax sugar of generator implementation. The syntax of generator is to modify the function with * and modify the steps with yield. However, yield only supports the return of promise or thunk functions. So if you need an await function, the await function does not need to be declared by async, just return a promise.

function promise () {
    return Promise.resolve('hello');
}

async function _await() {
   try {
     let res = await promise(); // 发现了没?
     console.log(res);
   } catch (e) {
     console.error(e);
   }
}

So as long as you return a promise, you can be await in any async function. I hope the question owner can understand this. So why don't I return a promise in the list function