2

I need to proces some data. I can do it in sync and async way like this (simplified):

  1. sync way:

    for (var i in input) {
        result += input[i]
    }
    
  2. async way

    function f(input,cb) {
      var result;
      if (!input) {
        setTimeout(function() {cb(result)},500);
      } else {
        f(input.slice(1),function(r) {
          result+=input[0];
        });
      }
    }
    

Is it possible to rewrite async code using generators? I wish I had some For loop code instead of recursion.

7
  • 2
    What are you trying to achieve? I don't see a point in processing this data in asynchronous way, unless it takes a lot of time and you don't want to block the event loop. Also, in this example you could just use the .join() method: result = input.join('');. Commented Jun 8, 2017 at 15:32
  • 1
    By the way, your async code using callbacks is overcomplex. Doing input.slice(1) at each iteration is not a performant way... Commented Jun 8, 2017 at 15:34
  • 1
    @Michał Perłakowski. yeah, It is just an example. In reality, I'm fetching data asynchronously from Internet, I have no input[] array. I want to process async data but to avoid recursive callbacks - is it possible? Commented Jun 8, 2017 at 15:37
  • 1
    @user2106769 Yes, it's possible. Read about promises and async functions. But we can't help you without having some more specific example of your code. Commented Jun 8, 2017 at 15:42
  • "Is it possible to rewrite async code using generators? I wish I had some For loop code instead of recursion." What is actual issue with code at Question? Commented Jun 8, 2017 at 16:24

1 Answer 1

0

Using await (a newer ES2017 technology that is built on generators in ES6), and assuming, as you've said:

  • you have multiple items (in this case ['apple', 'peach', 'banana'])
  • you wish to perform some async operation on them
  • You wish to avoid callbacks and .then() (which is a good idea if you're on node 7+ or current browsers)

Then:

var doThing = async function (input) {
    return new Promise(function(resolve, reject) {
        setTimeout(function(){
            resolve(`Result for ${input}`)
        }, 2000);
    });
}


var start = async function(listOfThings){
    var result = await Promise.all(listOfThings.map(doThing))
    console.log('All done', result)
}

start(['apple', 'peach', 'banana'])

Will return:

All done [ 'Result for apple', 'Result for peach', 'Result for banana' ]

To get some data from the network instead, you can simply replace the the setTimeout with superagent or (if you want to write your own query string encoding, URL handling etc) fetch.

Sign up to request clarification or add additional context in comments.

9 Comments

async/await does not use generators. It uses similar mechanisms, but is in no way based on them.
Thanks @bergi. I've edited my answer to clarify and add a reference to Eich's statement re: generators and await.
Why is aync/await usage necessary where javascript at Answer includes use of Promise constructor and Promise.all()?
@guest271314 No, the .then() results in more complex code (it creates additional scopes) and achieves the result with longer code (which is inefficient).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.