我正在尝试将两个数组的id(event.id)合并到一个数组中。我遇到了一个问题,我不明白如何将这些数组合并到它们的函数之外。我知道有一种方法可以使用Promise.all
来实现,但不知道该怎么做。感谢您的时间。
function getpinnacle() {
return new Promise(function (resolve, reject) {
var options = {sportId: 29};
pinnacle.getFixtures(options, function(err, response, body) {
if (err) throw new Error(err);
var pinnFixtures = [];
body.league.forEach(function(leagues){
leagues.events.forEach(function(event){
if (event.status == 'O'){
pinnFixtures.push({
'id': event.id,
'homeTeamName': event.home,
'awayTeamName': event.away
});
};
});
});
resolve(pinnFixtures);
});
var options = {sportId: 29, oddsFormat: "DECIMAL"};
pinnacle.getOdds(options, function(err, response, body) {
if (err) throw new Error(err);
var pinnOdds = [];
body.leagues.forEach(function(league){
league.events.forEach(function(event){
event.periods.forEach(function(period){
if (period.moneyline !== undefined) {
pinnOdds.push({
'id': event.id,
'homeTeamOdds': period.moneyline.home,
'drawOdds': period.moneyline.draw,
'awayTeamOdds': period.moneyline.away
});
};
});
});
});
resolve(pinnOdds);
});
});
}
module.exports = getpinnacle;
答案 0 :(得分:0)
为了拥有一个可供您使用这两个数组的上下文,您可以将每个回调包装在一个promise中,然后使用Promise.all()
等待结果:
function getpinnacle() {
var options = {sportId: 29};
const fixtures = new Promise(function(resolve, reject){
pinnacle.getFixtures(options, function(err, response, body) {
if (err) throw new Error(err);
var pinnFixtures = [];
body.league.forEach(function(leagues){
leagues.events.forEach(function(event){
if (event.status == 'O'){
pinnFixtures.push({
'id': event.id,
'homeTeamName': event.home,
'awayTeamName': event.away
});
};
});
});
resolve(pinnFixtures);
});
});
var options = {sportId: 29, oddsFormat: "DECIMAL"};
const odds = new Promise(function(resolve, reject){
pinnacle.getOdds(options, function(err, response, body) {
if (err) throw new Error(err);
var pinnOdds = [];
body.leagues.forEach(function(league){
league.events.forEach(function(event){
event.periods.forEach(function(period){
if (period.moneyline !== undefined) {
pinnOdds.push({
'id': event.id,
'homeTeamOdds': period.moneyline.home,
'drawOdds': period.moneyline.draw,
'awayTeamOdds': period.moneyline.away
});
};
});
});
});
resolve(pinnOdds);
});
});
return Promise.all([fixtures, odds]);
}
之后,您可以致电getPinnacle().then(function(results){...})
,其中结果是数组[fixtures, odds]
。
答案 1 :(得分:0)
我要重构代码的方法是将getFixtures
和getOdds
分成两个独立的函数,每个函数都返回一个promise。然后getPinacle将return Promise.all(getFixtures(), getOdds())
答案 2 :(得分:0)
你可以像这样使用promise.all
function getpinnacle() {
var promises = [];
var fixturePromise = new Promise( (resolve, reject) => {
///add your code here and resolve from inside you getFixture method
});
promises.push(fixturePromise);
var oddPromise = new Promise( (resolve, reject) => {
//add your getOdds method here and resolve this promise too
});
promise.push(oddPromise);
Promise.all(promises).then( (response) => {
var fixtureResponse = response[0];
var oddResponse = response[1];
//add your extra logic here
});
}