Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
// promise 
// .....................................................................
// promise 物件包含兩個 callback function 參數 (一個成功 ok 和一個失敗 err)
// 會依據執行結果給出其中一個 callback
 
// function a, b, c 都會傳出 promise
// (這裡都手動指定成敗)
function a (){
  console.log('a: 漂向北方')
  
  return new Promise(function(ok, err) {
    setTimeout( function(){ 
      console.log('a: 別問我家鄉')
      var r = Math.round(Math.random())
      if(r === 1){
        console.log('a ok 轉麥')
        ok('高聳古老的城牆 擋不住憂傷')
      } else {
        console.log('a err 落拍')
        err('!! 落拍')
      }
      
    }, 100 );
  })
}
function b (v){
  console.log('b: '+v)
  
  return new Promise(function(ok, err) {
    setTimeout( function(){ 
      console.log('b: 我漂向北方')
      var r = Math.round(Math.random())
      if(r === 1){      
       console.log('b ok 轉麥')
       ok('家人是否無恙')
      } else {
        console.log('b err')
        err('!! 落拍')
      }
    }, 1000 );
  })
}
function c (v){
  console.log('c: '+v)
  
  return new Promise(function(ok, err) {
    setTimeout( function(){ 
      console.log('c: 肩上沉重的行囊 盛滿了惆悵')
      var r = Math.round(Math.random())
      if(r === 1){ 
        console.log('c ok 轉麥')
        ok('#rap')
      } else {
        console.log('c err')
        err('!! 落拍')
      }
    }, 10 );
  })
}
// promise then
// .....................................................................
 
// 使用 .then() 串聯其他動作,.then() 用來接收一個 promise,也傳出一個 promise
// 這裡是前一個都 ok 的樣子:
// a().then(b).then(c)
// a(*ok*).b(*ok*).c(*ok*)
// Promise(*ok*, err).Promise(*ok*, err).Promise(*ok*, err)
// 這裡是可以看到有人辣漆的樣子:
// a()
//   .then(result=>{
//   console.log('a 提詞 ('+ result +')')
//   return b(result)
  
// },(err)=>{
//   console.log('a ('+ err +')')
//   return b(err)
// })
//   .then(result=>{
//   console.log('b 提詞 ('+ result +')')
//   return c(result)
  
// },(err)=>{
//   console.log('b ('+ err +')')
//   return c(err)
// })
// async 
// .....................................................................
// async 裡面有非同步函式,
// await 是一個運算子,可以暫停 async function 行程
// 可以用 await 來排成同步函式
 
async function abc() {
  var ma;
  var mb;
  var mc;
  
  try {
    ma = await a();
  } catch (e) {
    console.log('catch '+e)
    ma = e
  }
  
  try {
    mb = await b(ma);
  } catch (e) {
    console.log('catch '+e)
    mb = e
  }
  
  try {
    mc = await c(mb);
  } catch (e) {
    console.log('catch '+e)
    mc = e
  }
  console.log('async a:'+ ma +', b: '+ mb +', c: '+ mc );
  return ('async a:'+ ma +', b: '+ mb +', c: '+ mc );
}
abc()
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
oooooopro
0viewers