---
# System prepended metadata

title: JavaScript Async 範例

---

# JavaScript Async 範例

XMLHttpRequest - 請於新增單一則 post 完成並收到回應後，再發出拿到所有 post 的請求，當拿到貼文後，再發出刪除最後一篇貼文的請求
```javascript=1
function reqListener() {
  var oReq2 = new XMLHttpRequest();
  oReq2.addEventListener("load", function () {
    var oReq3 = new XMLHttpRequest();
    oReq3.addEventListener("load", function (e) {
      console.log(e.target.responseText);
    });
    oReq3.open("DELETE", "http://localhost:3000/posts/5");
    oReq3.send();
  });
  oReq2.open("GET", "http://localhost:3000/posts");
  oReq2.send();
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);

var data = {};
data.title = 'The Adventures of Tom'
data.author = 'Mark Twain'

oReq.open("POST", "http://localhost:3000/posts");
oReq.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
oReq.send(JSON.stringify(data));
```

---

JQuery - 請於新增單一則 post 完成並收到回應後，再發出拿到所有 post 的請求，當拿到貼文後，再發出刪除最後一篇貼文的請求

```javascript=1
$.ajax({
  method: 'POST',
  url: 'http://localhost:3000/posts',
  data: {
    title: 'The Adventures of Tom',
    author: 'Mark Twain'
  }
})
  .done(function(value) {
    $.get( "http://localhost:3000/posts").done(function(value) {
      $.ajax({
        method: 'DELETE',
        url: 'http://localhost:3000/posts/11',
      })        
    });
  })
  .fail(function(value) {
    console.log('error', value);
  })
  .always(function(value) {
    console.log('complete', value);
  });
```

---

fetch - 請於新增單一則 post 完成並收到回應後，再發出拿到所有 post 的請求，當拿到貼文後，再發出刪除最後後一篇貼文的請求

```javascript=1
postData('http://localhost:3000/posts', {
  title: 'The Adventures of Tom',
  author: 'Mark Twain'
})
  .then(data => getData('http://localhost:3000/posts'))
  .then(data => deleteData('http://localhost:3000/posts/30'))
  .catch(error => console.error(error))

function postData(url, data) {
  // Default options are marked with *
  return fetch(url, {
    body: JSON.stringify(data), // must match 'Content-Type' header
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, same-origin, *omit
    headers: {
      'content-type': 'application/json'
    },
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, cors, *same-origin
    redirect: 'follow', // manual, *follow, error
    referrer: 'no-referrer', // *client, no-referrer
  })
    .then(response => response.json()) // 輸出成 json
}

function getData(url){
  return fetch(url)
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });
}

function deleteData(url, data) {
  // Default options are marked with *
  return fetch(url, {
    method: 'DELETE', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, cors, *same-origin
  })
    .then(response => response.json()) // 輸出成 json
}
```

---

fetch - 請嘗試更新 id 為 100 的貼文，完成並收到回應後，再發出拿到所有 post 的請求，如果發生錯誤請使用console.error() 抓住錯誤

```javascript=1
putData('http://localhost:3000/posts/100', {
  title: 'The Adventures of Tom1',
  author: 'Mark Twain1'
})
  .then(data => getData(data)) // JSON from `response.json()` call
  .catch(error => console.error(error))

function putData(url, data) {
  // Default options are marked with *
  return fetch(url, {
    body: JSON.stringify(data), // must match 'Content-Type' header
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, same-origin, *omit
    headers: {
      'content-type': 'application/json'
    },
    method: 'PUT', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, cors, *same-origin
    redirect: 'follow', // manual, *follow, error
    referrer: 'no-referrer', // *client, no-referrer
  })
    .then(response => response.json()) // 輸出成 json
}

function getData(url){
  return fetch(url)
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });
}

```

---

rxjs - 請接續上一範例，不要讓 observable 在 got value 5 的時候結束，延後一秒，產生 got value 6 ，再結束

```javascript=1
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

const observable = new Observable(subscriber => {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.next(3);
  setTimeout(() => {
    subscriber.next(4);
  }, 1000);
  setTimeout(() => {
    subscriber.next(5);
    subscriber.complete();
  }, 2000);
});
 
console.log('just before subscribe');
const observer = {
  next: function(x) { console.log('got value ' + x); },
  error: function(err) { console.error('something wrong occurred: ' + err); },
  complete: function() { console.log('done'); }
}
const subscription = observable
.pipe(map(item => (+item + 1)))
.subscribe(observer);

console.log('just after subscribe');
```

