在循环中链接嵌套的承诺 [英] chaining nested promises in a loop

查看:27
本文介绍了在循环中链接嵌套的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Promise 有点陌生,并且坚持以下练习.

I am kind of new to promises and are stuck on the following exercise.

我有一个值数组,我想对每个值执行异步调用.在回调中,我想对第一次调用的结果执行另一个调用.

I have an array of values and I want to execute an async call on each one. In the callback, I want to execute another call on the outcome of the first call.

基本上,我的不满在于:执行顺序应该是'1x2x3x'但顺序是'123xxx'

Basically, my frustration is in the following: The order of execution should be '1x2x3x' but the order is '123xxx'

换句话说,当第一个承诺的子/嵌套承诺尚未完成时,循环已经进入下一次迭代..

In other words, the loop is already going to the next iteration when the sub/nested promise of the first promise is not fullfilled yet..

var values = ["1", "2", "3"];

function do(val) {
  var deferred = Q.defer();


  asyncCall(val)
  .then( function( response ) {
    console.log(val); 
    asyncCall(response)
    .then( function ( response ) {
      console.log('x');
      deferred.resolve(true)
    });
  });

  return deferred.promise;
}

var result = do(values[0]);

values.forEach( function(f) {
  result = result.then(do(f));
}

可能有一个简单的解决方案,但我坚持使用它.

There is probably an easy solution but I'm stuck on it.

推荐答案

你不需要延迟,那就是 延迟反模式 自从承诺链以来你就有了.

You don't need the deferred, that's the deferred anti pattern you have there since promises chain.

此外,如果您希望 .then 处理程序等待它解决,则必须从 .then 处理程序返回一个承诺.

Also, you have to return a promise from a .then handler if you want it to wait for it to resolve.

你可以简单地使用 for 循环:

You can simply use a for loop:

function do(val) {

  var q = Q();
  for(var i = 0; i < val; i++){
    q = q.then(asyncCall.bind(null,i))
         .then(console.log.bind(console))
         .then(console.log.bind(console,"x"));
  }

  return q; // in case you want to chain
}

小提琴.

注意:绑定只是固定函数调用的值.在这种情况下,由于第一个参数(this 值)为空,它的作用类似于 function(fn,arg){ return function(arg){ return fn(arg);}} 也就是说,它将函数调用转换为部分应用程序" - 有关更多信息,请参见 MDN 文档.

Note: Bind just fixates the value for the function call. In this case since the first param (the this value) is null it acts like function(fn,arg){ return function(arg){ return fn(arg); }} that is, it translates a function call to a "partial application" - for more info see the MDN docs.

这篇关于在循环中链接嵌套的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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