【发布时间】:2018-11-11 01:39:55
【问题描述】:
我有一个 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);
});
});
});
}
【问题讨论】:
-
听起来
secResp.body的participants属性是null。 -
添加一个 'retiurn' ..... return getPlayersInMatch(req.params.name).then ....
-
@RobertRowntree - 这如何影响
participants的值导致.then(function(participants) -
this is an array- 什么是数组?JSON.parse(secResp.body)?如果是这样,那么它永远不会有.participants属性,因为数组没有。虽然您可以将任何您喜欢的属性添加到数组中,但由于数组是由 JSON.parse“创建”的,因此它永远不会有自定义属性 -
调试步骤 1 ...
console.log(secResp.body)- 将输出添加到问题
标签: javascript node.js promise request