luciotato / waitfor

Sequential programming for node.js, end of callback hell / pyramid of doom
MIT License
531 stars 29 forks source link

Cannot be used inside a foreach loop? #33

Closed JanisE closed 8 years ago

JanisE commented 9 years ago

waitfor.js:

var oProcessor = {}
oProcessor.Process = function (sText, fCallback)
{
    console.log('sText = ', sText);
    setTimeout(function ()
    {
        fCallback(null, sText);
    }, 1000);
}

var wait = require('wait.for');

['text1', 'text2'].forEach(function (sText)
{
    console.log('Processed = ', wait.forMethod(oProcessor, 'Process', sText));
});
$ node waitfor.js 

/home/janis/waitforissue/node_modules/wait.for/waitfor.js:21
        if (!fiber) throw new Error('wait.for can only be called inside a fibe
                          ^
Error: wait.for can only be called inside a fiber
    at Object.wait.applyAndWait (/home/janis/waitforissue/node_modules/wait.for/waitfor.js:21:27)
    at Object.wait.forMethod (/home/janis/waitforissue/node_modules/wait.for/waitfor.js:71:21)
    at /home/janis/waitforissue/waitfor.js:16:35
    at Array.forEach (native)
    at Object.<anonymous> (/home/janis/waitforissue/waitfor.js:14:20)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
luciotato commented 9 years ago

Try this:

waitfor.js:

var oProcessor = {}
oProcessor.Process = function (sText, fCallback)
{
    console.log('sText = ', sText);
    setTimeout(function ()
    {
        fCallback(null, sText);
    }, 1000);
}

var wait = require('wait.for');

// this function runs "in a Fiber"
function  testFunction(){
    ['text1', 'text2'].forEach(function (sText)
    {
    console.log('Processed = ', wait.forMethod(oProcessor, 'Process', sText));
    });
}

console.log('app start');
wait.launchFiber(testFunction);
console.log('after launch');
$ node waitfor.js 
JanisE commented 9 years ago

Yes, it worked! Thank you!

pascalfossouo commented 6 years ago

@luciotato Please Having the same error but don't know how to make it work

const Web3 = require('web3'); const Web3Utils = require('web3-utils'); var express = require('express'); var app = express(); var each = require('foreach'); var request = require('request'); var fs = require('fs'); var logger = fs.createWriteStream('log.txt', { flags: 'a' // 'a' means appending (old data will be preserved) }); var wait = require('wait.for');

var parseXlsx = require('excel'); var stringSearchTable = [5,10]; var allStringSearchTable = [];

parseXlsx('test.xlsx', function(err, data) { if(err) throw err; //console.log('data : ',data);

for(var i=0; i< data.length ; i++){

   var stringSearch = '';

   for(var j=0; j< 8 ; j++){

        if(stringSearchTable.includes(j)){
            var str =  data[i][j].replace(' ', '+');
            stringSearch +=  str.replace(/ /g,'+') + "+";
            //console.log('string :', stringSearch);
        }

    }       
    allStringSearchTable.push(stringSearch);    

}

//console.log('data : ',allStringSearchTable);

var api = 'http://maps.google.com/maps/api/geocode/json?address='; var apiKey = '&sensor=false&region=CA';
var nothing = 'N/A'; var options = { url: process.env.APIURL + 'api/Jurisdictions', //headers: headers, }; each(allStringSearchTable, function (value, key, array) {

   options.url = api + value + apiKey;
   console.log('url :',value);
    getJSON(options,function(err, body) {
        if (err) {
          console.log(err.stack);
          return res.status(500);
        }

        //console.log('data  : ',body.results);

        if(body.status == 'OK' ||  body.status == 'OVER_QUERY_LIMIT'){
            var strTxt = key;
             each(body.results, function (val, k, ar) {
                  strTxt += "\t" + val.geometry.location.lat + "\t" + val.geometry.location.lng + "\t" +val.place_id;
             });
             logger.write(strTxt + "\n");
             logger.end();
        }else{
             logger.end();
             logger.write(key + "\t" + nothing + "\t" + nothing + "\t" + nothing + "\n");
             logger.end();
        }
    });

    var ms=Math.floor(Math.random()*40000);
    console.log('waiting',ms);
    wait.forMethod(callbackOnTimer,ms);

});

});

function getJSON(options, callback){ request(options, function(err, res, body) { if (err) return callback(err); try { callback(null, JSON.parse(body)); } catch (ex) { callback(ex); } }); };

function callbackOnTimer(ms,sleepCallback) { setTimeout(function() { return sleepCallback(); }, ms); }