box-lin / miniblog

https://bboxlin.github.io/miniblog/
MIT License
0 stars 0 forks source link

Javascript Promise Example #16

Open box-lin opened 1 year ago

box-lin commented 1 year ago

$$ a = a+b $$

$a = a+b$


const getTodos = (url) => {
    return new Promise((resolve, reject)=> {
      const request = new XMLHttpRequest();
      request.addEventListener('readystatechange', () => {
        if (request.readyState === 4 && request.status === 200) {
          const data = JSON.parse(request.responseText)
          resolve(data)
        } else if (request.readyState === 4) {
          reject('could not fetch')
        }
      })
      request.open('GET', url)
      request.send()
      return data
    })
}

// Resolved
getTodos('https://jsonplaceholder.typicode.com/todos').then((data)=>{
  console.log('promise resolved', data)
}).catch((err)=>{
  console.log('promise reject', err)
})

// Reject
getTodos('https://jsonplaceholder.typicode.com/todos4444').then((data)=>{
  console.log('promise resolved', data)
}).catch((err)=>{
  console.log('promise reject', err)
});