Skip to content Skip to sidebar Skip to footer

Promise.all - Promise Within Promise Not Being Resolved

Hello I am continuing to learn promises and am struggling with how to correctly use Promise.All or whether or not I should be using it in this situation. I am connecting to a data

Solution 1:

Here's my best stab at this problem:

// Promisified search, resolves to response arrayfunctiongetBingSearchesPromise() {
    returnnewPromise((resolve, reject) => {
        GetBingSearches().toArray((err, response) => {
            if (err) {
                reject(err);
            } else {
                resolve(response);
            }
        });          
    });
}

// get first image url for a search term, resolves to an image URLfunctiongetBingImagePromise(term) {
    returnnewPromise((resolve, reject) => {
        Bing.images(term, {count: 1}, (err, res, body) => {
            if (err) {
                reject(err);
            } else {
                resolve(body.value[0].contentUrl);
            }
        });
    });
}


// no need to pass req or res into here// returns promise, resolves to array of images URLsfunctionGetSearches() {
    returngetBingSearchesPromise().then(searchResponses => {
        // get all imageslet promises = searchResponses.map(searchItem => {
            returngetBingImagePromise(searchItem.SearchTerm);
        });
        returnPromise.all(promises);
    })    
}

// then inside your request handler where you have req and res, you can do thisGetSearches().then(images => {
    res.json(images);
}).catch(err => {
    console.log(err);
    res.status(500).end();
});

Because your code was pretty far off and did not include a words description of what you are trying to do, this is an educated guess about you're trying to accomplish. If I got the objective wrong with my guess, you can either just learn from this and apply it to your actual problem or I can delete my answer.

Summary of Changes:

  1. Promisify async operations separately, then build all logic with promises (no plain callbacks). This could probably be done even better if we could see the code for GetBingSearches() which should probably have some arguments passed into it rather than be hard-wired to do a specific type of search.

  2. Get the searches promise and wait for it with .then() to get an array of results.

  3. In that .then() handler, use .map() to fetch each image URL and create an array of promises.

  4. Wait for that array of promises with Promise.all().

  5. Separate out req and res from this code because only the final response needs to use res so this way you code can be more usable and you can just call this code from the response handler and get the result without passing res into it.

  6. Add error handling for all errors. Propagate all errors back up the chain.

  7. Never use for/in to iterate an array (it iterates properties of an object, not just array elements). If your desired result is a 1-to-1 array, then .map() is perfect for that. Otherwise, in ES6, use for/of to iterate an array.

Post a Comment for "Promise.all - Promise Within Promise Not Being Resolved"