Javascript Generator Functions

來源:互聯網
上載者:User

標籤:fine   settime   asc   row   undefined   XA   led   function   next   

Example

/*/*function需要用*標記yiled 可以返回多個值*/function* calculate(a,b){    yield a + b;    yield a + a;    throw ‘some error‘//遇到錯誤立即返回,所以以下代碼不會被執行    yield a * a;    return b + b;}let gen = calculate(1,3);//直接調用generator function並非傳回值,而是返回一個generator的函數對象console.log(gen);//需要單獨一次調用next()函數,依次返回yield的值//return返回的對象done是true。如果直接到沒有return到函數結尾,返回的對象done是true,value是undefined//如果函數已經結束(done是true)。再調用next(),會一直是{value: undefined, done: true}gen.next(); //{value: 4, done: false}gen.next();//{value: 2, done: false}gen.next(); //Uncaught some errorgen.next();//{value: undefined, done: true}gen.next();
Example - Generator functions和Promisevar promiseGenerator = function*(){yield new Promise(r=>setTimeout(r,2000))yield 5;}
let gen = promiseGenerator()gen.next().value.then(v=>console.log("hi. I am back."))//返回Promise對象。調用then 列印log資訊gen.next().value//列印第二個yield的結果 5/*從結果上看會先列印5,然後顯示log資訊。因為Promise的方法是非同步會等待2秒。所以yield並不保證Promise的方法執行完才調下一個yield的結果。如果想要5在Promise方法結束後顯示可以在Promise中的then中調用generator的next()方法一下的codegen.next().value.then(v=>{ console.log("has passed 5 seconds. will write the value: ",gen.next().value)})*/

  

Javascript Generator Functions

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.