在 NodeJS 中使用 bluebird promises 的链函数

Chain functions using bluebird promises in NodeJS

我很抱歉又问了一个 Promise 问题,但是我不太明白,在阅读了这里的大量问题和解释之后,我仍然在挣扎。

所以在我的 nodejs 项目中,我尝试做三件事。

1) 从 Facebook 获取用户信息 API

graph.get(message.user, function getUserInfo(err, res) {
     console.log(res)
}

2) 从另一个 API

获取用户列表
request.get('https://api-url/api/users', {
        'auth': {
            'bearer': 'bearerAuth'
        }
    })

3) 检查 Facebook 用户的姓名是否与我从 API 返回的 JSON 数据中的姓名相匹配,然后将其交给用户。

let aPieceOfData = "";

Bluebird.promisifyAll(graph.get(message.user))
    .then(function(res) {
        // this should give me the response from the Facebook API which is the user
        // Then pass the response to the next .then(function(){})
    })
    .then(function(res) {
       request.get('https://api-url/api/users', {
         'auth': {
           'bearer': 'bearerAuth'
         }
         const apiData = JSON.parse(response.body);
         for (i in apiData) {
          if (res.username == apiData[i].username) {
            // if the username matches the user name then save some data to a variable outside this scope so I can access it
            aPieceOfData = apiData[i].item;
          }
         }
       })
    })
    .catch(function(err) {
        console.log(err, "<<<<<<<");
    })

格式可能有点不对。但是我很难理解 promises 是如何工作的,以及我如何在我的链式函数之间传递数据,而不是最后将它保存在我的函数之外以便我可以使用它。

有人可以给出一些解释吗and/or一些指向初学者更友好的解释的链接。

基于示例from the doc

var fs = Promise.promisifyAll(require("fs"));

fs.readFileAsync("myfile.js", "utf8").then(function(contents) {
    console.log(contents); }).catch(function(e) {
    console.error(e.stack); });

我觉得应该是这样的:

var g = Bluebird.promisifyAll(graph);
g.getAsync(message.user)
    .then(function (res) {
        // this should give me the response from the Facebook API which is the user
        // Then pass the response to the next .then(function(){})
        return res;
    })
    .then(function (res) {
        return request.get('https://api-url/api/users', {
            'auth': {
                'bearer': 'bearerAuth'
            }
        });
    })
    .then(function (response) {
        const apiData = JSON.parse(response.body);
        for (i in apiData) {
            if (res.username == apiData[i].username) {
                // if the username matches the user name then save some data to a variable outside this scope so I can access it
                aPieceOfData = apiData[i].item;
            }
        }
    })
    .catch(function (err) {
        console.log(err, "<<<<<<<");
    });