简体   繁体   English

如何链接一系列返回promises的函数,并需要不同的参数?

[英]How to chain a series of functions which return promises, and require different parameters?

I have two asynchronous functions, which use parameters already acquired somehow: 我有两个异步函数,它们使用已经以某种方式获取的参数:

var a = getUserinput();
var b = getUserinput();
var c = getUserinput();
var d = getUserinput();


var func1 = function(valA, valB){
     var deferred = $q.deferred;
     //http call with valA, valb...
     // when complete, resolve deferred
     return deferred.promise;
}

var func2 = function(valC, valD){
     var deferred = $q.deferred;
     //http call with valC, valD...
     // when complete, resolve deferred
     return deferred.promise;
}

I want to execute func1 and then func2 . 我想执行func1然后执行func2 The problem is that I can't find a way to do this successfully while being able to provide parameters to func2 . 问题是,在能够为func2提供参数的同时,我找不到成功完成此操作的func2

For example, if I do 例如,如果我这样做

func1(a, b).then(func2(c, d));

func2 executes before func1 is done. func2func1完成之前执行。

How do I execute func2 only after func1 is done? 如何在func1完成后执行func2

func

Provide anonymous function and place func2 invocation in it: 提供匿名函数并在其中放置func2调用:

func1(a, b).then(function() {
    func2(c, d);
});

If it helps, I recently took the first release of the rogue written for UNIX in C and rewrote it for javascript to work in a browser. 如果它有所帮助,我最近在C中为UNIX编写了第一个流氓版本,并将其重写为javascript以在浏览器中工作。 I used a technic called continuation to be able to wait for key entry by the user because in javascript the are no interrupts. 我使用了一种名为continuation的技术,能够等待用户输入密钥,因为在javascript中没有中断。

So I would have a piece of code like this: 所以我会有一段这样的代码:

void function f() {

  // ... first part

  ch = getchar();

  // ... second part

}

that would be transformed in 那将会改变

function f() {

  // ... first part

  var ch = getchar(f_cont1);

  return;
  // the execution stops here 

  function f_cont1 () {

    // ... second part
  }
}

the continuation is then stored to be reuse on a keypressed event. 然后存储继续以在keypressed事件上重用。 With closures everything would be restarted where it stoped. 有了闭包,一切都会在停止的地方重新启动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM