An async
function can contain an await
expression that pauses the execution of the async function and waits for the passed Promise
's resolution, and then resumes the async
function's execution and returns the resolved value.
Remember, the await
keyword is only valid inside async
functions. If you use it outside of an async
function's body, you will get a SyntaxError
.
function getHtml(url) { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = () => { resolve(xhr.responseText); }; xhr.onerror = () => { reject(xhr.statusText) }; xhr.send(); }).then( val=>{ return getTitle(val); } ); } function getTitle(html){ return html.substring(html.indexOf('<title>')+7,html.indexOf('</title>')); } async function printTitle(){ console.log(new Date().getTime()); // 暂停执行,直到Promise被resolve或reject后,继续执行 var title = await getHtml('https://www.baidu.com'); console.log(new Date().getTime(),title); } printTitle();