Promise
fetch 返回的就是 Promise
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
   |  fetch("http://127.0.0.1:4523/m1/2751993-0-default/project/list") .then(function (response) {          return  response.json() }) .then(function (json) {   console.log("json", json) }) .catch(function (err){      console.log("err", err) }) .finally(function (other) {            console.log("other", other) })
 
 
 
  | 
 
async,await
基于 Promise 的一个语法糖
await在等待的过程中js可以执行其他任务,这是因为 await 底层是基于 Promise 和事件循环机制实现的
1 2 3 4 5 6 7 8 9 10 11 12 13
   | 
  async function test(){   const response = await fetch('http://127.0.0.1:4523/m1/2751993-0-default/project/list');      console.log("response", response)   const json = await response.json()   console.log("json", json) } test() 
 
 
 
 
  | 
 
- 我们不能在全局或者普通函数中直接使用 await 关键字,会报错, “await“只在异步函数中有效
 
- 如果我们想在最外层中使用 await, 那么需要先定义一个异步函数, 然后在函数体中使用它
 
1 2 3 4
   | async function f() {   await someAsyncOperation(); } f();
 
  | 
 
或者更简洁的写法
1 2 3
   | (async => await someAsyncoperation(); })();
 
  | 
 
参考
视频
文章