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的用法 #55

Open
yixiaosi1314 opened this issue Jun 28, 2021 · 1 comment
Open

async和await的用法 #55

yixiaosi1314 opened this issue Jun 28, 2021 · 1 comment

Comments

@yixiaosi1314
Copy link

No description provided.

@yinyinnnn
Copy link

async 、await的用法

async用于声明异步函数,返回值为一个 Promise 对象
async function fn() {
    console.log('Hello world!');
}

console.log(fn().constructor); // Promise()
// 这里证明其返回值为一个 Promise 对象;

promise对象有resolve和reject两种状态,相应的有.then()和.catch()两种方法来获取返回值

async /await 需要在function外部写async,在内部需要等待执行的函数前书写await

*注:await必须写在async函数中
   async function fn() {
       console.log(1);
       new Promise(function(resolve, reject) {
           setTimeout(function() {
               console.log(2);
           });
       });
       console.log(3);
   }
fn();
结果为:
1
3
2

await 会等到后面的 Promise 返回结果后才会执行 async 函数后面剩下的语句,也就是说如果 Promise 不返回结果(如 resolve 或 reject),后面的代码就不会执行

async function fn() {
    console.log(1);
    await  new Promise(function(resolve, reject) {
        setTimeout(function() {
            console.log(2);
        });
    });
    console.log(3);
}
fn();
结果为:
1
2
async function fn() {
    console.log(1);
    await  new Promise(function(resolve, reject) {
        setTimeout(function() {
            console.log(2);
            resolve();
        });
    });
    console.log(3);
}
fn();
结果为:
1
2
3

20180814092340280

@Dogtiti Dogtiti added the Cbayel label Jul 1, 2021
@Dogtiti Dogtiti removed the Cbayel label May 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants