首页 > 解决方案 > Promise.all 里面 promise.all 是 Promise 的好习惯吗?

问题描述

我不知道promise.all内部promise.all解决方案是否是一个好习惯。我不确定。

我需要从用户数组中获取信息,然后通过这些信息响应,我需要发送消息通知。

let userList = ['key1', 'key2', 'key3']; //More data can arrive
let promises = userList.map((userKey,index)=>{
            return GetUserById(db.ref(`Users/${userKey}`));
});

Promise.all(promises).then(responses =>{
  let notificationPromises = responses.map((user)=>{
      sendNotification('message', user.token);
  });
  return Promise.all(notificationPromises)
}).then(()=>{
   //notifications were sent
   ...
};

Promise.all用嵌套解决它是个好主意吗?

标签: javascriptpromise

解决方案


虽然这会起作用,但很难理解为什么这是一个比仅调用then()第一组请求更好的选择——记住,then()它也会返回一个 Promise。这对我来说不仅更短,而且更清晰。很明显,您正在向每个用户发送通知:

let userList = ['key1', 'key2', 'key3']; //More data can arrive
let promises = userList.map((userKey,index)=>{
            return GetUserById(db.ref(`Users/${userKey}`))
            .then(user => sendNotification('message', user.token) )
});

Promise.all(promises)
.then(()=>{
    //notifications were sent
    // ...
});

map()ps 在您的代码中,您需要从回调中返回一些内容,否则notificationPromises将是一个空值数组:

Promise.all(promises).then(responses =>{
    let notificationPromises = responses.map((user)=>{
        return sendNotification('message', user.token); //<< add return
    });

推荐阅读