Appearance
返回值
本节目标:理解“返回值”的核心思路,并能把它用于实际开发或面试表达。
**返回一个** **Promise** **对象。**return返回:函数内部return语句返回的值,会成为then方法回调函数的参数。 async function f()
`{`
`return` `'hello`world'; } f().then(v
`=>`console.log(v)) //
`"hello` `world"`抛出错误:async函数内部抛出错误,会导致返回的 Promise 对象变为reject状态。 抛出的错误对象会被catch方法回调函数接收到。 async function f()
`{`
`throw` `new`Error('
出错了'); } f().then(
`v` `=>`console.log(v),
`e` `=>`console.log(e) ) //
`Error:` 出错了作为返回值的Promise对象的状态变化 async函数返回的 Promise 对象,必须等到内部所有await命令后面的 Promise 对象执行完,才会发生状态改变,除非遇到return语句或者抛出错误。也就是说,只有async函数内部的异步操作执行完,才会执行then方法指定的回调函数。如: async function getTitle(url)
`{`
`let` `response` `=` `await`fetch(url);
`let` `html` `=` `await`response.text();
`return`html.match(/<title>([\s\S]+)</title>/i)[1]; } getTitle('https://tc39.github.io/ecma262/').then(console.log) // "ECMAScript 2017 Language Specification" 上面代码中,函数getTitle内部有三个操作:抓取网页、取出文本、匹配页面标题。只有这三个操作全部完成,才会执行then方法里面的console.log。
