Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于async await的特性的理解 #7

Open
lovelmh13 opened this issue Aug 4, 2019 · 0 comments
Open

关于async await的特性的理解 #7

lovelmh13 opened this issue Aug 4, 2019 · 0 comments

Comments

@lovelmh13
Copy link
Owner

lovelmh13 commented Aug 4, 2019

async 特性: 函数前写async,会把函数强制包装成一个promise

await特性1: 会阻塞线程,没有拿到axios结果之前,不会执行end

await 特性2: 求值,会直接返回promise.then里面的东西(不仅仅是用于promise)

// 中间件(洋葱模型)
// 不要随便用async await,碰到异步再用
app.use(async (ctx, next) => { // async特性:函数前写async,会把函数强制包装成一个promise
    const axios = require('axios');
    const start = Date.now();
    const res = await axios.get('http://www.baidu.com');    
    // await特性1: 会阻塞线程,没有拿到axios结果之前,不会执行 const end = Date.now();及其后面的代码(相当于promise.then)
    const end = Date.now();
    console.log(end-start);
    console.log(res); // 返回了html代码,而不是promise {{html}}   
   // await特性2:求值,会直接返回promise.then里面的东西, 而不是返回promise(不仅仅是用于promise)
});

关于特性2:求值 的说明:

在没有加await的时候,返回了promise对象

image

在加了await以后,则返回了User对象(promise.then)

image

参考:Node.js+KOA2 从0到1打造超好用Web框架

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant