简体   繁体   English

Javascript承诺混乱以按顺序执行两个功能

[英]Javascript promise confusion for executing two functions in order

Right now I have funcA, funcB, arrayA and arrayB. 现在我有funcA,funcB,arrayA和arrayB。 In funcA, arrayB will populate itself by requesting some external information and the time for doing this is varied. 在funcA中,arrayB将通过请求一些外部信息来填充自身,并且执行此操作的时间有所不同。 I want it to execute funcB after arrayB.length == arrayA.length, and arrayB is a global variable that its content will be used in funcB. 我希望它在arrayB.length == arrayA.length之后执行funcB,并且arrayB是一个全局变量,其内容将在funcB中使用。 I assume that I need to use JQuery deferred and promise..so I tried this 我假设我需要使用JQuery deferred和promise..so,所以我尝试了

     var arrayB = [];
     var hi = funcA();
     hi.then(funcB());

     funcA(){
            var Dfd = $.Deferred();
            arrayB.forEach(function(x, i){
                   some external retrieval;
                   if (arrayB.length == arrayA.length){
                         Dfd.resolve(arrayB);
                   }
             })

        return Dfd;
     }

But this doesn't help. 但这无济于事。 How should I change it? 我该如何更改?

arrayB.forEach won't do a thing. arrayB.forEach不会做任何事情。 It's empty. 它是空的。 Forget all this functions and deferred. 忘记所有这些功能并推迟。

fetch('/mydata.json')
  .then(function(response) {
    //save your data from response to arrayB
    //call your funcA
  })
  .catch((error) => {
    console.log(error);
});

I don't know why you needed that: 我不知道你为什么需要这个:

if (arrayB.length == arrayA.length){
   Dfd.resolve(arrayB);
}

But feel free to make a check before calling funcA. 但是,请在致电funcA之前先进行检查。

我这样做可以解决问题:

  hi.done(function(){funcA()});

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

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