JavaScript的异步编程:承诺VS发电机 [英] JavaScript asynchronous programming: promises vs generators

查看:138
本文介绍了JavaScript的异步编程:承诺VS发电机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

承诺与发生器可以编写异步code。我不明白为什么这两种机制在ECMA脚本介绍6.当它是最好用的承诺,并在发电机?

Promises and generators allow you to write asynchronous code. I do not understand why both of these mechanisms are introduced in ECMA script 6. When is it best to use the promises, and when the generators?

推荐答案

在这两种技术之间没有反对。他们一起共存互补很好。承诺给你的能力得到一个异步操作这确实尚未公布结果。它解决了末日问题金字塔。因此,而不是:

There is no opposition between these two techniques. They coexist together complementing each other nicely. Promises give you capability to get result of an asynchronous operation which does not available yet. It solves Pyramid of Doom problem. So instead of:

function ourImportantFunction(callback) {
  //... some code 1
  task1(function(val1) {
    //... some code 2
    task2(val1, function(val2) {
      //... some code 3
      task3(val2, callback);
    });
  });
}

你可以写:

function ourImportantFunction() {
  return Promise.resolve()
    .then(function() {
        //... some code 1
        return task1(val3)
    })
    .then(function(val2) {
        //... some code 2
        return task2(val2)
    })
    .then(function(val2) {
        //... some code 3
        return task3(val2);
    });
}

ourImportantFunction().then(callback);

不过,即使承诺你必须写在异步方式code - 你必须始终传递回调函数。编写异步code是更难然后同步。即使承诺时,code是巨大的,难以看到算法(当然,这是非常主观的,有人可以用它争辩。但对于大多数程序员,我认为这是真的)。因此,我们要编写同步方式异步code。这就是发电机来帮助我们。因此,而不是code以上,你可以这样写:

But even with promises you must write code in asynchronous fashion - you must always pass callbacks to the functions. Writing asynchronous code is much harder then synchronous. Even with promises when the code is huge it becomes difficult to see the algorithm (well, it's very subjective, someone can argue with it. But for majority of programmers I think it's true). So we want to write asynchronous code in synchronous fashion. That's where generators are coming to help us. So instead of code above you can write:

var ourImportantFunction = spawn(function*() {
    //... some code 1
    var val1 = yield task1();
    //... some code 2
    var val2 = yield task2(val1);
    //... some code 3
    var val3 = yield task3(val2);

    return val3;
});

ourImportantFunction().then(callback);

其中最简单可行的产卵实现可以是这样的:

where simplest possible spawn realization can be something like:

function spawn(generator) {
  return function() {    
    var iter = generator.apply(this, arguments);

    return Promise.resolve().then(function onValue(lastValue){
      var result = iter.next(lastValue); 

      var done  = result.done;
      var value = result.value;

      if (done) return value; // generator done, resolve promise
      return Promise.resolve(value).then(onValue, iter.throw.bind(iter)); // repeat
    });
  };
}

正如你所看到的(一些异步函数的结果任务{N} )必须是一个承诺。你不能用回调做到这一点。

As you can see value (result of some asynchronous function task{N}) must be a promise. You can't do this with callbacks.

剩下要做的就是落实产卵技术到语言本身。因此,我们将产卵异步收益等待,并即将 ES7异步/的await

What remains to do is to implement spawn technique into language itself. So we are replacing spawn with async and yield with await and are coming to ES7 async/await:

var ourImportantFunction = async function() {
    //... some code 1
    var val1 = await task1();
    //... some code 2
    var val2 = await task2(val1);
    //... some code 3
    var val3 = await task3(val2);

    return val3;
}

我建议你看此影片更明白这一点和其他一些未来的技术。如果这个家伙说你得太快,放慢速度的右下角打(设置,或只是把[ + &LT ; ])

I recommend you to watch this video to more understand this and some other coming techniques. If the guy speaks too fast for you, slow down the speed of playing ("settings" in right bottom corner, or just push [shift + <])

什么是最好的:只是回调,或承诺,或承诺搭配发电机 - 这是非常主观的问题。回调此时最快的解决方法可能的(本土的承诺现在表现非常糟糕)。搭配发电机承诺给你机会写异步code在同步方式。但现在,他们要慢很多,然后简单的回调。

What is the best: just callbacks, or promises, or promises with generators - this is very subjective question. Callbacks is the fastest solution possible at this time (performance of native promises are very bad now). Promises with generators give you opportunity to write asynchronous code in synchronous fashion. But for now they much slower then simple callbacks.

这篇关于JavaScript的异步编程:承诺VS发电机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆