javascript - Nodejs Promise 无法解析/没有返回数据

标签 javascript node.js promise request

我有一个 Promise 函数,它进行两次请求调用并在第二次调用完成后解析。第二次解析调用还取决于第一次调用的数据。但在 then 函数中,我得到的变量返回值为 null。任何帮助将不胜感激。

编辑:secResp.body 具有正确的数据,它不为空

const express = require('express');
const request = require('request');
const app = express();
const port = process.env.PORT || 5000;

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

app.get('/api/currentMatch/:name', function(req, res, next){
    getPlayersInMatch(req.params.name).then(function(participants){
        //this is null
        console.log(participants);
    }).catch(function (err) {
     console.log(err);
    });
})

function getPlayersInMatch(name){
    return new Promise(function(resolve, reject){
        request.get({
            url: api_url
        }, function(firstErr, firstResp, body){
            if(firstResp.StatusCode != 200){
                reject(firstErr);
            }
            var accountId = JSON.parse(firstResp.body).id;
            request.get({
                url: api_url2 + 'accountId=' + accountId
            }, function(secErr, secResp, body){
                if(secResp.StatusCode != 200){
                    reject(secErr);
                }
                //this is not null, this is an array
                var participants = JSON.parse(secResp.body).participants;
                resolve(participants);
            });
        });
    });
}

最佳答案

我重写了你的代码 request-promise 。我发现您的代码的主要问题是它太复杂了。简化事情可以更容易地发现你做错了什么。

const rp = require('request-promise')
const app = express();
const port = process.env.PORT || 5000;

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

app.get('/api/currentMatch/:name', function(req, res, next){
    getPlayersInMatch(req.params.name)
        .then(console.log)
        .catch(console.error)
})

const getPlayersInMatch = async name => {
    const id = await rp(api_url)
        .then(res => JSON.parse(res.body).id)

    const participants = await rp(api_url2 + 'accountId=' + accountId)
        .then(res => JSON.parse(res.body).participants)

    return { id, participants }
}

关于javascript - Nodejs Promise 无法解析/没有返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53245123/

相关文章:

javascript - jQuery & Objects,试图制作一个轻量级的小部件

node.js - 如何在node.js中扩展q.promise?

angularjs - 如何在angularjs中链接promise错误函数

javascript - 如何在没有 "indentation pyramids"的情况下正确表达任意 Promise 链?

node.js - 我应该在哪里存储 code_verifier(使用 PKCE 的 oauth 2.0 代码授权流程)

Javascript 从多组复选框中解析 JSON 数组

javascript - 如何将一个变量分配给另一个变量加一个常量

javascript - 如何将映射的键名更改为嵌套对象?

parsing - 是否有用于 nodejs 的(JSON 或 XML)流解析器?

node.js - Node 应用程序无法连接到 MongoDB,但仅在 Docker 中