Javascript Promise将值推入数组(仅从函数还是外部?) [英] Javascript Promise push value into array (only from function or outside?)

查看:91
本文介绍了Javascript Promise将值推入数组(仅从函数还是外部?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些承诺和一个Promise.all:

I have some promises and a Promise.all:

array = [];


  var one = new Promise(function(resolve, reject) {
    // Do stuff
    setTimeout(function() {
      resolve('One Done');
      array.push('one');
    }, 5000);
  });


  var two = new Promise(function(resolve, reject) {
    // Do Stuff
    resolve('Two Done');
    array.push('two');
  });


  Promise.all(array).then(values => {
    console.log(values);
  });

我们知道这不起作用,因为array.push必须在外面。

We know this doesn't work because array.push needs to be outside.

我目前有一些需要通过promises调用的函数,以便最终可以在Promise.all中使用它。

I currently have a few functions which I need to have called by promises so that finally I can have it in Promise.all.

建议像这样从promise内部调用该函数:

Would it be advisable to call the function from inside the promise like this:

    function dosomething() {
        // does something
        array.push('something');
    }

  var mypromise = new Promise(function(resolve, reject) {
    dosomething();
    resolve('Did something');
  });

还是有更明智的方法?

推荐答案

Promise.All期望有一个Promise数组,并且将等待所有Promise都被兑现,从而为您提供每个Promise或catch的结果(如果其中任何一个失败)。

Promise.All expects an array of promises, and will wait until all promises are fullfilled, providing you with the results of each Promise or a catch if any of them fails.

如果您愿意使用不仅仅是字符串的方法来解析对象,则可以使用任何类型的对象来解析它们,然后可以使用任意方式使用结果,因此您可以避免弄乱promise中的数组,而可以将工作项作为一个单元来解析,并在异步评估后使用所有必需的结果。

You can resolve them with any type of object if you are willing to resolve it with more than just a string, and you can use the results afterwards in any way you want, so you could avoid messing with the array inside from the promise and instead resolve the "work item" as a unit and use all required results after the async evaluation.

您也可以尝试执行以下操作:

You could instead try to do this:

   var valuesArray=[];

   var prom1 = new Promise(function(resolve, reject) {
        // Do stuff
        setTimeout(function() {
          resolve({ msg: 'One Done', data : 'one'});
          // array.push('one');
        }, 5000);
      });

    var prom2 = new Promise(function(resolve, reject) {
        // Do Stuff
        resolve({ msg: 'Two Done', data : 'two'});
        // array.push('two');
      });

   var promisesArray= [prom1,prom2]; 

   Promise.all(promisesArray).then(values => {
        // do stuff with values here
        console.log(values[0].msg);
        console.log(values[1].msg);
        valuesArray.push(values[0].data);
        valuesArray.push(values[0].data);
      });

这篇关于Javascript Promise将值推入数组(仅从函数还是外部?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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