0

I'm new to JavaScript so sorry if the question is too dumb.

I have an async function getPartners() in file1.js wich returns an array like this:

return Promise.resolve(partners);
['1','2','3']

In file2.js I have an array with partnerIds and an emptyArray. My goal is when I call getPartners() in file2.js, emptyArray becomes equivalent to the function's return value. In other words I'd like to push the returned values to the emptyArray.

Currently I can get the values this way:

let emptyArray = listItems();
emptyArray.then((result) => {
  console.log(result);
});

My problem is that if I try to console.log(emptyArray) outside of the .then, it's empty. I'd like to filter it too, after getting the values from the promise so I need to save the values into an array which I can call later in the code.

How can I do that?

EDIT: This is what I want to achieve:

const { getPromiseResult } = require('./list');

let existingIds = ['1','2','3'];

let emptyArray = getPromiseResult();
emptyArray.then((resultArrayfromPromise) => {
  console.log(resultArrayfromPromise) // ['2','3','4']
  // filter the results by the existingIds array's elements
  // get result: ['1','2','3','4']
  // and get this result in a new filtered array which I can reach from the outside
});

filteredArray.dosomeotherstuff();
Con Troll
  • 159
  • 1
  • 1
  • 8

1 Answers1

0

Since ES7, you can use async/await to get rid of then. await waits for operation to complete, and if there is a return value assigns it to the variable.

But you can only use the await in an async function so wrap your codes in it.

async function run() {
    const { listItems } = require('./list');
    let existingIds = ['1','2','3'];
    let emptyArray = await getPromiseresult(); 
    console.log(emptyArray); // now it's not empty
    filteredArray.dosomeotherstuff();
}

run();
Mustafa Burak Kalkan
  • 1,132
  • 21
  • 28