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 #4

Open
ibufu opened this issue Aug 31, 2016 · 0 comments
Open

简记async await #4

ibufu opened this issue Aug 31, 2016 · 0 comments

Comments

@ibufu
Copy link
Owner

ibufu commented Aug 31, 2016

简述:

async 用于声明一个包含异步操作的函数。
在 async 函数中,用 await 表示一个异步操作(Promise 对象)。
当函数执行到 await 时,函数会暂停,保存上下文环境,等待执行结果。

例子1:

function timeout(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}


async function asyncPrint(value, ms) {
    await timeout(ms);
    console.log(value);
}

asyncPrint('hello world', 50);

例子2:

(async function() {
    const result = await callApi('/directNet/getCampInfo', { campId });
        console.log(result);
}());

循环:

要在for循环中使用,不能使用forEach。

异常:

try {
     await foo();
} catch (e) {
     console.log(e);
}

then操作:

async函数返回的是一个promise对象,所以可以在后面进行链式操作。

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