返回列表

Promise 及 Generator

默认分类 2016/12/02 03:35

手动回调:

const nextStep = (i) => {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            resolve(i+1);
            alist.next(i+2); 
        }, 2000);
    })
}

var a = function*() {
    for (var i=0,len=4; i<len; i++) {
        var serverData1 = yield nextStep(i);
        console.log('status:%s', serverData1);
        //alist.next(i+1); 
    }
};

var alist = a();
alist.next(1);

自动回调:

var Promise = require('bluebird');

const nextStep = (i) => {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            resolve(i+1);
            //alist.next(i+2); 
        }, 2000);
    })
}

var a = function*() {
    for (var i=0,len=3; i<len; i++) {
        var serverData1 = yield nextStep(i);
        console.log('status:%s', serverData1);
        //alist.next(i+1); 
    }
    return "whew all done";
};

var alist = Promise.coroutine(a);
var blist = alist().then(function(result) {
    console.log('===============');
    console.log(result);
},function (fail) {
    //Todo
});
// alist.next(1);

async和和await

// node.exe --harmony-async-await test.js
const f = (i) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(i + 1);
        }, 2000);
    });
};

const testAsync = async() => {
    for (var i = 0, len = 4; i < len; i++) {
        const t = await f(i);
        console.log('>>' + t);
    }
};

testAsync();