代码之家  ›  专栏  ›  技术社区  ›  Kevin

承诺并不像我期望的那样

  •  1
  • Kevin  · 技术社区  · 10 年前

    我使用Express进行路由,使用Sequelize进行数据库管理。

    app.get('/api/users/:username', (req, res) => {
      let username = req.params.username;
      findChattersPerRole()
        .then(chattersPerRole => {
          console.log('instakbot should\'ve been added by now...');
        });
    });
    

    函数findChattersPerRole返回一个对象,其中每个用户的用户名和角色作为另一个对象。

    const findChattersPerRole = () => {
      return fetch('https://tmi.twitch.tv/group/user/instak/chatters')
        .then(parseJSON)
        .then(r => {
          let chatters = r.chatters;
          let chattersPerRole = Object.keys(chatters).map(role => {
            return chatters[role].map(username => {
              console.log('findOrCreateViewer will be executed after this');
              findOrCreateViewer(username, role);
              return {
                username: username,
                role: role
              };
            });
          });
          return Promise.resolve(flattenDeep(chattersPerRole));
        }).catch(err => {
          console.log(`Error in fetch: ${err}`);
        });
    };
    

    console.log('instakbot should\'ve been added by now...'); 在我的查看器插入数据库后执行,因为在我的函数findChattersPerRole中,我已经使用函数findOrCreateViewer插入了它们。我希望这会发生,因为在我的路线中,我编写控制台。解析findChattersPerRole()时的日志。。。

    const findOrCreateViewer = (username, role) => {
    
      return Viewer.findOrCreate({
        where: {
          username
        },
        defaults: {
          instakluiten: 5,
          role
        }
      }).spread((unit, created) => {
        console.log('unit is: ', unit.dataValues.username);
        if(created){
          return `created is ${created}`;
        }else{
          return unit;
        }
      });
    
    };
    

    然而,在我的终端中,你可以看到这不是发生的方式……为什么我的承诺没有在预期的时间执行? Screenshot of my terminal

    2 回复  |  直到 10 年前
        1
  •  2
  •   Felix Kling    10 年前

    这个 return {username: ...} 之后 findOrCreateViewer(username, role); 函数调用后立即发生,并且 之前 已插入任何数据。这也意味着 return Promise.resolve(flattenDeep(chattersPerRole)); 在插入任何数据之前发生,等等。

    你说 findOrCreateViewer 返回一个promise,因此在继续其他操作之前,需要等待该promise被解析(即,等待数据插入后)。

    你想要 chattersPerRole 成为一个承诺的数组,并且只继续 之后

    这很容易做到 Promise.all :

    const findChattersPerRole = () => {
      return fetch('https://tmi.twitch.tv/group/user/instak/chatters')
        .then(parseJSON)
        .then(r => {
          let chatters = r.chatters;
          let chattersPerRole = Object.keys(chatters).map(
            role => chatters[role].map(username => {
              console.log('findOrCreateViewer will be executed after this');
              return findOrCreateViewer(username, role).then(
                () => ({username, role})
              );
            });
          );
          return Promise.all(flattenDeep(chattersPerRole));
        }).catch(err => {
          console.log(`Error in fetch: ${err}`);
        });
    };
    

    现在,承诺得到了回报 findChattersPerRole 将得到解决 之后 所有的承诺都得到了回报 findOrCreateViewer 已解决。

        2
  •  2
  •   Bergi    10 年前

    承诺没有魔力。返回promise并不意味着调用函数会阻塞,而是可以很容易地链接回调以处理结果。您需要使用

    function findChattersPerRole() {
      return fetch('https://tmi.twitch.tv/group/user/instak/chatters')
        .then(parseJSON)
        .then(r => {
          let chatters = r.chatters;
          let chattersPerRole = Object.keys(chatters).map(role => {
            return chatters[role].map(username => {
              console.log('findOrCreateViewer will be executed after this');
              return findOrCreateViewer(username, role).then(() => {
    //        ^^^^^^                                   ^^^^^
                return {
                  username: username,
                  role: role
                };
              });
            });
          });
          return Promise.all(flattenDeep(chattersPerRole));
    //                   ^^^ get a promise for an array of results from an array of promises
        }).catch(err => {
          console.log(`Error in fetch: ${err}`);
        });
    }