Html 知识点

promise

用途用来解决回调陷阱
最简示例

new Promise(resolve => {
  setTimeout(() => {
    resolve('hello')
  }, 2000)
}).then(res => {
  console.log(res)
})

二级回调改写例子

new Promise(resolve => {
    setTimeout(() => {
      resolve('hello')
    }, 2000)
  }).then(val => {
    console.log(val) //  参数val = 'hello'
    return new Promise(resolve => {
      setTimeout(() => {
        resolve('world')
      }, 2000)
    })
  }).then(val => {
    console.log(val) // 参数val = 'world'
  })

async

完整单词: asynchronous

async function getData_1 () {
    return '100'
}

等效于

function getData_2 () {
    return new Promise((resolve, reject) => {
        resolve('100')
    })
}

await 就是等待 async执行完,才会执行后面的东西, 等待的东西是异步的,它就会阻塞当前代码,
别担心, 它只能在async函数里使用, 虽然阻塞,但是是异步的

async function getData_1 () {
    return '100'
}

function getData_2 () {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('200')
        }, 2000)
    })
}

async  function run () {

    const data_1 = await getData_1();
    console.log(data_1);

    const data_2 = await getData_2();
    console.log(data_2);
}

run ();

从网页下载json数据

fetch

标准写法

fetch('http://example.com/answer', {answer: 42})
  .then(function(response) {
    if(response.ok)
    {
     return response.json();
    }
   
  })
  .then(
      function(jsonData)
      {
        console.log(json.Data);
      }
  )
   

修改 HTTP 头

var url = 'https://example.com/profile';
var data = {username: 'example'};

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers: new Headers({
    'Content-Type': 'application/json'
  })
}).then(
res => res.json()
)
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

await 写法

(async function () {
 const data = await (await fetch(dataSource)).json();
 }());
 

async function run()
{
   const response= await fetch(url);
   if(!response.ok)
   {
      console.log(reponse);
   }
   const data=await(response.json());
   
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值