1. 异步函数被调用后会先后返回两个值,第一个返回值是一个promise对象(在异步函数被调用后立即返回),第二个返回值是异步函数return语句的返回值。第二个返回值将成为第一个返回值promise对象的value属性值。

MDN Web Docs是这样描述异步函数的返回值:
instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
示例代码如下所示:
function sleep (time) { return new Promise((resolve) => setTimeout(resolve, time)); } async function test_async() { console.log('start time: ' + new Date()); await sleep(20000); console.log('finish time: ' + new Date()); return 'hello world'; } var o = test_async(); console.log(o);
示例代码的运行结果如下所示:
异步函数调用的返回值
2. await后面一般紧跟一个promise对象或一个异步函数的调用。因为一个异步函数调用的返回值是一个promise对象,所以,await后面紧跟一个异步函数调用,本质就是await后面紧跟一个promise对象,即:await 异步函数名() = await 一个promise对象 。
3. "await 一个promise对象" 将获得这个promise对象状态为fulfilled或rejected时value属性值。"await 异步函数名()" 将获得这个异步函数第二次返回的返回值(即return语句的返回值)。
示例代码1:
async function hello() { return "Hello" }; async function handleHello() { // hello()的值是hello()第一次的返回值(即是一个promise对象) // 而await hello()的值是hello()第二次的返回值(即return语句的返回值) let result = await hello(); console.log({result: result}); // output: Hello } handleHello();
await hello()的值是hello()第二次返回的值
示例代码2
async function hello() { return "Hello" } async function handleHello() { let firstReturnValue = hello() let secondReturnValue = await firstReturnValue console.log({ firstReturnValue: firstReturnValue, secondReturnValue: secondReturnValue }) } handleHello()
异步函数hello()的第一个返回值和第二个返回值
4. await是阻塞等待的,等待一个promise对象的状态由pending变为fulfilled或rejected,或者说,等待一个promise对象被resolve或reject。
5. Promise.prototype.then()是阻塞等待的,等待一个promise对象的状态由pending变为fulfilled或rejected,或者说,等待一个promise对象被resolve或reject。
6. 使用async关键字声明一个函数为异步函数,在异步函数内和模块顶层才能使用await关键字,否则就会报错。
MDN Web Docs是这样描述的:
await is only valid in async functions and the top level bodies of modules.
7. 创建promise对象时回调函数里的参数resolve和reject是由JavaScript engine预定义的函数。
const testPromise = new Promise((resolve, reject) => { // 这里的resolve和reject是由JavaScript engine预定义的函数 setTimeout(() => { resolve('testPromise'); }, 5000); });
8. Promise.prototype.then(callback1, callback2)的返回值是一个promise对象,这个promise对象是resolve到then(callback1, callback2)中callback1或callback2的返回值,就看是callback1被调用了还是callback2被调用了。
示例代码如下所示:
Promise.resolve('success').then(() => 1, () => 2) Promise.reject('fail').then(() => 1, () => 2)
await 一个promise对象与
一个promise对象.then(resolvedCallback, rejectedCallback)
是等价的,都在阻塞等待一个promise对象的状态由pending变为fulfiled或rejected,然后对这个promise对象的状态为fulfiled或rejected的属性值进行相关后续处理。
其中,.then(),当这个promise对象的状态为fulfiled时则调用resolvedCallback处理,当这个promise对象的状态为rejected时则调用rejectedCallback处理。


还没有评论,来说两句吧...