Executing promises in array with Promise.all breaks them

前端 未结 1 1405
故里飘歌
故里飘歌 2021-01-21 14:52

I have an array of userIds that I use in getOrdersByUserId() to get the orders placed by these users for a specific month:

function getOrdersByUserId(userId, mon         


        
相关标签:
1条回答
  • 2021-01-21 15:13

    You have a common misunderstanding: You don't execute promises. Promise.all doesn't "run" anything. A promise is just a means of watching an operation to know when it's done and whether it worked or failed.

    In your case, the operations are started by apiService.getOrdersList, as soon as you call it.

    What you're seeing suggests that

    1. The API service doesn't like you sending it eight simultaneous requests (perhaps it rate-limits), and

    2. The promise from the API service resolves with a value that isn't valid JSON rather than rejecting when it can't handle #1 (which is unfortunate, it should reject, not resolve).

    Nothing about using Promise.all breaks these operations. But apparently, running eight of these operations in parallel breaks.

    You could run them in series (one after another):

    userIds.reduce((p, userId, index) => {
        return p.then(results => {
            return getOrdersByUserId(userId, month)
             .then(orders => {
                 results[index] = orders;
                 return results;
             });
        });
    }, Promise.resolve([]))
    .then(results => {
        // `results` is an array of results, in the same order as `userIds`
    })
    .catch(err => {
       console.log(err);
    });
    

    Each call to getOrdersByUserId waits for the previous one to complete; the final result is an array of results in the same order as the userIds array.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题