异步库ForLoop

时间:2016-08-03 21:08:44

标签: javascript loops asynchronous

我尝试运行此代码并使用异步库获取say.speak命令以一次运行一个。但是,说话命令全部同时发生。虽然console.logs以正确的顺序发生!有谁知道解决方案?

控制台解决方案(时间和事件名称):

12:00:00 PM

Mach&马特

下午4:00:00

设置帮助! Microsoft Social 3.0 Chicago

下午4:30:00

AV Check - Microsoft Social 3.0 Event Chicago

代码

var api = require('./api.js');
var say = require('say');
var async = require('async');
var S = require('string');
var i = 0;

api.getEvents(function (err, result) {
    if (err)
        console.log(err);
    else {
        //Intro();

        async.times(result.value.length, function (callback) {
            async.series([
                function (callback) { Time(result.value[i].start.dateTime, callback);},
                function (callback) { someAsyncTask(result.value[i].subject, callback); ++i;  },


            ])
        });

    }

});
// do two async series.. one for setup and one for read
// series 1: time convert, and send result.value[i] to series 2
// series 2: for loop to read out 
// optional callback

function Intro() {
    setTimeout(function () {
        say.speak('todays schedule is');
    }, 1000);
}

function someAsyncTask(event, callback) {
    setTimeout(function () {
        console.log(event);
        say.speak(event);
        // * returning err !== null will abort the execution
        // of all tasks and call finalCallback(err)
        // * result will be appended to the list of results returned to finalCallback()
        callback(/*err=*/null, /*result=*/event);
    }, 2000);
}


function Time(data, callback) {
    var cst = new Date(Date.parse(data));
    var time = cst.toLocaleTimeString();
    setTimeout(function () {
        console.log(time);
        say.speak(time);
    }, 2000)

    callback();
}

0 个答案:

没有答案