使用promise在循环内调用ajax

时间:2016-12-16 18:19:50

标签: javascript jquery ajax promise

大家好我试图在使用promise的循环中使用ajax,但我在循环内的第二个ajax调用不能用于ajax请求并继续执行。

这是我的代码:

@RunWith(PowerMockRunner.class)
public class MusicBroadcastReceiverUnitTest {
    private MusicBroadcastReceiver mReceiver;

    @Mock
    private Context mContext;

    @Mock
    private Intent androidIntent;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);

        mReceiver = new MusicBroadcastReceiver();
    }

    @Test
    public void testStartMusicRegistrationService() {
        try {
        PowerMockito.whenNew(Intent.class)
               .withArguments(String.class).thenReturn(androidIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        when(androidIntent.getAction())
          .thenReturn("com.android.music.metachanged");
        when(androidIntent.getStringExtra("artist"))
          .thenReturn("SampleArtist");

        mReceiver.onReceive(mContext, intent);

        ArgumentCaptor<Intent> argument = ArgumentCaptor.forClass(Intent.class);
        verify(mContext, times(1)).startService(argument.capture());

        Intent receivedIntent = argument.getValue();
        assertEquals("SampleArtist", receivedIntent.getStringExtra("artist"));
    }
}

当我从这一行 var general = []; var all_info =[]; var usuario =[]; var resultPromise = getProjects(); // Promise for a response. resultPromise.then(function(all_projects) { return $.when.apply($, all_projects.map(function (current_project, index){ var items = {}; items.name = current_project.key; items.children = [{"total_cpu": current_project.cpuhour_tot, "num_jobs" : current_project.num_jobs }]; return addUsers(current_project.key) .then(function(item_user) { info_user = {}; info_user.name = item_user.key; info_user.children = [{"total_cpu" : item_user.cpuhour_tot, "num_jobs": item_user.num_jobs }]; all_info.push(info_user); }); items.children.push(all_info); general.push(items) })); }) .then(function() { console.log("complete", general); }) .fail(function(jqxhr, textStatus, errorThrown) { console.log(errorThrown); }) 返回时,我需要将return addUsers...值包含到项目中,然后在执行其他循环到all_project之前,我必须这样做all_info

但无法访问general.push(items)

我缺少什么?

提前致谢!

2 个答案:

答案 0 :(得分:1)

替换.map()代替.forEach()使用$.when()Function.prototype.apply()usuario是一个数组; .push() value到数组。

resultPromise.then(function(all_projects) {
  return $.when.apply($, all_projects.map(function (current_project, index){
    var items = {};
    items.name = current_project.key;
    items.children = [{"total_cpu": current_project.cpuhour_tot, "num_jobs" : current_project.num_jobs }];
    return addUsers(current_project.key)
    .then(function(value) {
      console.log(value)
      usuario.push(value);
      // use value here before continues;
      // do stuff with `value` or `usuario` here
    });
  }));
})
.then(function() {
  console.log("complete", usuario)
})
.fail(function(jqxhr, textStatus, errorThrown) {
  console.log(errorThrown)
})

答案 1 :(得分:0)

阅读javascript的异步单线程特性可以帮助您了解此处发生的事情。

基本上是以下说明:

resultPromise.then(function(value) {
  usuario = value;
  // use value here before continues;
  console.log("first");
});

询问“在解决promise并清除执行堆栈时,将来某个时刻执行回调函数”。回调函数不会就地运行,实际上直到当前执行线程完成后才会运行。