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
3
  • 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). Commented Mar 1, 2019 at 23:24
  • @PatrickRoberts Fixed, thank you. Commented Mar 1, 2019 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. Commented Mar 1, 2019 at 23:25

2 Answers 2

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)
 ));
Sign up to request clarification or add additional context in comments.

Comments

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));

Comments