1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const fetch = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
// resolve('success');
reject('error');
}, 2000);
});
};
const testAsync = async() => {
try {
return await fetch();
} catch (error) {
return Promise.reject(error);
}
};
testAsync().then((result)=> {
console.log('这是成功的--->' + result);
}).catch((error)=> {
console.log('这是失败的--->' + error);
});;

async函数返回的一个 Promise, 调用耗时函数前面加 await 关键字,返回成功的值,可以使用 try..catch 来进行捕获错误。上面的代码可以模拟一次请求的过程,最基本用法差不多都包括了

点我运行

Promise.then是异步的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var promise = new Promise(function (resolve){
console.log("inner promise"); // 1
resolve(42);
});
promise.then(function(value){
console.log(value); // 3
});
console.log("outer promise"); // 2
----------
inner promise // 1
outer promise // 2
42 // 3

为啥这样

更多的关于 Promise 看下面的这本电子书,就不扯了,啦啦啦。

参考:
JavaScript Promise迷你书(中文版)