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

查看:207
本文介绍了在循环中链接嵌套的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 处理程序,如果你想让它等待它解决。

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 值)为null,它的行为类似于函数(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.

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

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