2

I have a question. I am currently learning how to use promises but I have run into a problem that I haven't found the answer for after extensive searching. I am trying using map to get an array of promises that are the result of a then block to process in a Promise.all, yet the following does not work, what is going wrong here?

let promises = myArray.map(result => 
    {
        searchPromise(result.type).then((searchReply) => 
        {
            return processReply(result, searchReply)
        });
    }
);

Promise.all(promises).then(c => console.log(c)); //array of Undefined, but 
                                                 //want to get results from
                                                 //processReply function
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • Agreed there are some syntax errors, but you're probably getting an array of undefined because `myArray.map(...);` is not returning anything (implicit return of `undefined`). – Scott Rudiger Mar 01 '19 at 23:24
  • @PatrickRoberts Fixed, thank you. –  Mar 01 '19 at 23:24
  • 1
    @user87002 You're missing a return statement. Should be `return searchPromise(...` Alternatively you could remove the curly braces on your arrow function body. – Paul Mar 01 '19 at 23:25

2 Answers2

4

Your map function is not returning anything, only your then function:

let promises = myArray.map(result => 
    {
        return searchPromise(result.type).then((searchReply) => 
        {
            return processReply(result, searchReply)
        });
    }
);

Alternatively, omit the curly braces as stated in the comments, to force a return:

let promises = myArray.map(result => 
    searchPromise(result.type).then((searchReply) =>  processReply(result, searchReply)
 ));
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

You're likely getting an array filled with undefined because your call to myArray.map was not returning anything, thus implicitly returning undefined. Assuming searchPromise and processReply both return a Promise, this should work:

let promises = myArray.map(result => {
  return searchPromise(result.type).then((searchReply) => {
    return processReply(result, searchReply)
  });
});

Promise.all(promises).then(c => console.log(c));
Scott Rudiger
  • 1,224
  • 12
  • 16