我有一个 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/