美文网首页
异步、Promise和Generator

异步、Promise和Generator

作者: 狂风落尽深红色绿树成荫子满枝 | 来源:发表于2015-10-30 00:50 被阅读427次

我的一个小复习

假设你要运行一个任务管理器
输入id后,依次执行针对id的task1, task2, task3, task4...
在js这种异步语言里会是这样...

function taskRunner(id) {
  task1(id, function(){
    task2(id, function(){
      task3(id, function(){
        task4(id, function(){
          ...// callback hell
        })
      })
    })
  })
}

what a hell.
更糟糕的是,如果其中某个任务出错了,我怎么知道哪里出错了?

function asyncOperation() {
  setTimeout(function() {
    throw new Error("MyError!");
  }, 1000);
}
try { 
  asyncOperation();
} catch (e) {
  console.log("I cannot catch : ", e);
}

try和catch 没有用?
并不能捕获错误
那么...只能在异步回调里使用try

function asyncOperation() {
  setTimeout(function() {
    try {
      throw new Error("Error");
    } catch(e) {
      console.log("asyncOperation catch it: ", e.message);
    }
  }, 1000);
}

function run() {
  try { 
    asyncOperation();
  } catch (e) {
    console.log("I got no error", e);
  }
}

但是run调用者怎么知道发生了什么。接下来其他函数怎么知道发生了什么?
Nodejs社区采用一种error first的调用惯例
下一个回调可以收到err,判断,作出动作。但想象一下

function taskRunner(id) {
  task1(id, function(err, task1Output){
    if (err) handleError(err);
    doSomething(task1Output);
    task2(task1Output, function(err, res){
      if (err) handleError(err);
      task3(id, function(err){
        if (err) handleError(err);
        task4(id, function(err){
          if (err) handleError(err);
          ...// callback hell
        })
      })
    })
  })
}

如果doSomething出错了,错误如何捕获?

function taskRunner(id) {
  task1(id, function(err, task1Output){
    if (err) handleError(err);
    try {
      doSomething(task1Output);
    } catch(e) {
      handleError(e);
    }
    task2(task1Output, function(err, res){
      if (err) handleError(err);
      task3(id, function(){
        if (err) handleError(err);
        task4(id, function(){
          if (err) handleError(err);
          ...// callback hell
        })
      })
    })
  })
}

再如果对handleError想做出错处理,再如果我们在流程中嵌入了更多的同步和异步混用的代码,他们都要处理错误...What the fuck...

再也不想看这样的代码。我们的大脑并不能很好的切合这种模式。

回调与Promise

我们想写这样的代码...

task1().then(task2).then(task3)...

我们想做这样的错误处理

task1().then(task2, handleError).then(task3, handleError)...

他们创造了Promise,一个许诺,一个代表未来的值
一个一秒后才到来的十五
一个神奇的设计:

  1. then
  2. 状态与缓存
  3. 能串行(Promise链)
function Promise(f) {
  var cache;  // 未来的 值
  var dfs = []; // Promise链上Defferds链, deferds保存当前回调callback, 如果值到来了,传给桥Promise的resolve
  // 如果没解析,则添加到defferd链上,如果解析了,则调用df链上所有回调
  var status = "pending";

  this.then = function(callback) {
    return new Promise(function(resolve) {
      handle({
        callback: callback,
        resolve: resolve
      })
    })
  }

  function handle(df) {
    if (status == "pending") {
      dfs.push(df);
    } else if (status == "fulfiled") {
      var ret = df.callback(cache);
      df.resolve(ret);
    }
  }

  function resolve(value) {
    cache = value;
    status = "fulfiled";
    setTimeout(function() {
      dfs.forEach(function(df) {
        handle(df);
      })
    })
  }


  f(resolve);
}


var p1 = new Promise(function(resolve, reject){
  setTimeout(function() {
    resolve(15);
  }, 1000);
});

p1.then(function(value){
  console.log("task 1", value); 
  return value + 1;
}).then(function(value){
  console.log("task 2", value);
})

当然,还有个处理reject的部分,类似如此

对了,如果对new操作符有疑问, new 之后新的对象引用的闭包变量并不是函数中的变量,好奇怪。new 并不创建闭包。

> function f(){
  var a = 1;
  this.then = function(t){a = t};
  this.print=function(){console.log(a)}}
undefined
> x = new f()
f { then: [Function], print: [Function] }
> y = new f()
f { then: [Function], print: [Function] }
> x.then(5)
undefined
> x.print()
5
undefined
> y.print()
1
undefined

好了,我们已经能够通过Promise成功实现异步串行
假设我们啊,有个社工库,我们根据id能获取其中的用户名和密码。
考虑以下逻辑...

function getInfo(id, db) {
  return getUser(id).then(function(username) {
    return getPass(id).then(function(password){
      return {username: username, password: password}
    })
  })
}

我们倒是想这样
让user和name获取并行

function *getInfo(id, db) {
  var user = getUser(id);
  var pass = getPass(db);
  console.log("trying: ", yield user, yield pass);
}

function getUser(id) {
  console.log("get username");
  return new Promise(function(resolve, reject) {
    setTimeout(function(){
      resolve("name-" + id);
    }, 1000);
  })
}

function getPass(db) {
  console.log("get password");
  return new Promise(function(resolve, reject) {
    setTimeout(function(){
      resolve("db-" + db);
    }, 1000);
  })
}

显然我们更想要像同步代码一样书写

我们实现个async

function async(g) {
  return function() {
    var it = g.apply(this, arguments);

    function handle(result) {
      if (result.done)
        return result.value;
      return result.value.then(function(res) {
        return handle(it.next(res))
      })
    }
    return handle(it.next())
  }
}

var find = async(getInfo);
find("liu", "mydb");

就这么并行了

还可以串行

function *taskRunner(id) {
  var task1Output = yield getUser(id);
  var task2Output = yield getPass(task1Output);
  console.log("trying: ", task2Output);
}

have fun

相关文章

网友评论

      本文标题:异步、Promise和Generator

      本文链接:https://www.haomeiwen.com/subject/pxpxhttx.html