javascript Promise async await
Promise: 解决callback嵌套问题, .then()
等promise fulfilled后触发, .then()
和.catch()
可以嵌套
await 等待Promise fulfilled,返回其结果,或者抛出异常
async: 将一个普通方法转换成返回Promise
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
function deferedSayHello(){ return new Promise(function(resolve, reject){ setTimeout(function(){ resolve("javacoder.cn") },2000); }); } //Async 关键字将函数的返回值封装成Promise对象 async function hello() { console.log("befor deferedSayHello"); // 直接调用异步函数返回的是Pending状态的Promise console.log(deferedSayHello()) //await 等待Promise fulfilled, 返回的是结果或者异常 console.log(await deferedSayHello()) console.log("after deferedSayHello"); } hello() |
输出
befor deferedSayHello
Promise {<pending>}
javacoder.cn
after deferedSayHello
Posted in: IT人生
Comments are closed.