在另一个承诺中回复承诺

时间:2017-10-27 00:06:42

标签: javascript node.js promise

我试图返回依赖于其他承诺数据的承诺。我觉得我对于在另一个承诺完成时我应该如何开始一个承诺感到困惑。

我最终得到了

  

LDBManager.getRankByName出错:无法读取属性'然后'未定义的

index.js

try {                   // DATA IS UNDEFINED HERE ↓
  LDBManager.getRankByName(name).then(function (data) {
    console.log(data);
  });
} catch (e) {
  console.log('Error on LDBManager.getRankByName: ' + e.message);
}

LDB-manager.js

var LDBManager = {

    getSummonerByName: function (name) {

        return new Promise((resolve, reject) => {
            var url = LDB.url1;

            https.get(url, function (res) {
                var json = '';
                res.on('data', function (chunk) {
                    json += chunk;
                });
                res.on('end', function () {
                    var data = JSON.parse(json);
                    resolve(data);
                });
            }).on('error', function (e) {
                reject(e.stack);
            });
        })
            .catch(function () {
                console.log(`Couldn't retrieve summoner: ${name}`);
            });
    },

    getRankByName: function (name) {

        return this.getSummonerByName(name).then(function (summoner) {
            new Promise((resolve, reject) => {
                var url = LDB.url2;
                https.get(url, function (res) {
                    var json = '';
                    res.on('data', function (chunk) {
                        json += chunk;
                    });
                    res.on('end', function () {
                        var data = JSON.parse(json);
                        resolve(data); // ← DATA HAS WHAT I WANT HERE
                    });
                }).on('error', function (e) {
                    reject(e.stack);
                });
            })
                .catch(function () {
                    console.log(`Couldn't retrieve ranked stats for ${name}`);
                });
        });
    }
}

module.exports = LDBManager;

编辑:编辑返回,我可以在解析(数据)中看到我想要的值,但不能在控制台日志中看到。

感谢您的帮助!

1 个答案:

答案 0 :(得分:-1)

您需要将getSummonerByName包装到promise中。

return new Promise((resolve,reject)=>{
    this.getSummonerByName(name).then(summoner => {
       // put your http request code here. then resolve data that you want to resolve from the promise resolve callback and reject if error occur.
    })
});