Skip to content Skip to sidebar Skip to footer

Why I Can Not Push Value To Array Outside Of Function?

I have a function: static async assign( assigned_data, assigned_by ) { return new Promise( async ( resolve, reject ) => { let orders = []; await assigned_dat

Solution 1:

You are making the things complicated. Nesting async await is not a good idea, as it is difficult to debug.

There are several problems. Let's take a look on a working sample.

async function assign(assigned_data) {
  let orders = [];
  orders = await Promise.all(assigned_data.map(async(data) => {
    // find each order and update 
    return await Promise.all(data.map(async(order_id) => {
      return await call();
    }))
  }));
  console.log(orders);
}

async function call() {
  var promise = new Promise(function(resolve, reject) {
    setTimeout(function() {
      console.log('order');
      resolve('order');
    }, 2000);
  });
  return promise;
}

data = assign([
  [1, 2, 3],
  [1, 2, 3]
])

First of all, you need Promise.all to await the Promises formed by map.

Second, your nesting job still contains another array (I assume, thus you use map again). So you still need another Promise.all inside the previous Promise.all. (Please don't do this again for even complicated structure)

Lastly, put the real worker outside your nesting async-await loop.


Solution 2:

I think that, just callback! but, I don't test this. hm..

static async assign(assigned_data, assigned_by) {
    const orders = [];
    return new Promise( async ( resolve, reject ) => {
        assigned_data.map((data, index) => {
            data.assigned.map((order_id) => {
                this.findByIdAndUpdate(order_id, {
                    $set: {
                        current_assigned: {
                            user: data._id,
                            assigned_by: assigned_by,
                        },
                        last_assigned_at: Date.now(),
                        last_assigned_by: assigned_by,
                    },
                    $addToSet: {
                        assigned_history: {
                            user: data._id,
                            assigned_by: assigned_by,
                        }
                    },
                }, 
                (error, order) => {
                    error ? console.log('error', error) : console.log('order', order);
                    orders.push(order);

                    if(index === assigned_data.length-1) {
                        resolve(orders); // just callback
                    }
                });
            });
        });
    });
}

Sorry I don't see loop..

You can this. Javascript Map Array Last Item


Post a Comment for "Why I Can Not Push Value To Array Outside Of Function?"