// 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)
})
}
}
// a.js
const PublicClass = {
list: async () => {
... // 此处业务逻辑等待时间比较长,但最终会有一个返回结果
}
}
module.exports = {
test: async () => {
cost res = await PublicClass.list()
return res
}
}
// 这是文档给的例子
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)
})
}
}
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