1. Simple example
var sleep = function (time) { return new Promise(function (resolve, reject) { setTimeout(function () { resolve(); }, time); }) };
var start = async function () { // It's as intuitive to use as synchronous code here
console.log('start' ); await sleep(3000); console.log('end'); };
start();
The console outputs first start
, and 3秒
after a while, it outputs end
.
2. Basic Rules
- async means
这是一个async函数
,await只能用在这个函数里面
. - await means here
等待promise返回结果
, and then continue to execute. - await followed by
应该是一个promise对象
(of course, other return values are fine, just executed immediately, but that would be pointless...)
3、
await must appear in the code marked with async, indicating that a piece of thread code is suspended later, and the code after await asynchronous code indicates callback code .