我遇到了Promise的问题。我没有得到答案,因为异步。好吧,我认为这就是问题所在,因为当我运行代码时,我没有收到任何错误,但我也没有得到任何答案。
这是我的代码
'use strict'
import validator from "validator"
import cassandra from "./cassandra";
import timezone from "./timezone"
import requestRace from "./request"
exports.getUser = (req, res) => {
const getHistory = `SELECT inscriptionid,first_name,created,lastupdate,number,eventraceid ` +
`FROM inscription_data ` +
`WHERE userid = ${req.params.idUser} ` +
// `AND number IS NOT NULL ` +
`ALLOW FILTERING`;
if(req.params && validator.isUUID(req.params.idUser)) {
cassandra.execute(getHistory)
.then(ans => {
requestRace(timezone(ans.rows))
.then(aws => console.log("hola"))
.catch(err => console.log("error: ", err))
})
.catch(err => res.status(500).json({code: 500,data:{error: true,message: err}}))
}
}
和另一个
'use strict'
import axios from "axios"
const route = `https://ms.***.com/v1/races/`
function requestRace(params) {
var newArr = new Array(), newObj = {}, hola
params.map(obj => {
axios.get(`${route}${obj['eventraceid']}?apikey=pub_nLbIjlCWNKAdB_O3qgTaoQ`)
.then(res => {
newArr.push(creaJSON(obj, res.data))
// console.log("New:", newArr)
})
.catch(err => console.log("error: ", err))
})
return newArr.then(ho => {return ho} )
}
function creaJSON(obj,subojb) {
obj['race'] = subojb[`data`]
return obj
}
module.exports = requestRace
如果有人能看到我的错误,我会很感激,如果你能解释我的错误在哪里以及为什么
非常感谢你提前
答案 0 :(得分:0)
要解决我的问题,我必须使用async / await。这是它结束的方式
'use strict'
import validator from "validator"
import cassandra from "./cassandra";
import timezone from "./timezone"
import requestRace from "./request"
exports.getUser = (req, res) => {
const getHistory = `SELECT inscriptionid,first_name,created,lastupdate,number,eventraceid ` +
`FROM inscription_data ` +
`WHERE userid = ${req.params.idUser} ` +
`AND number IS NOT NULL ` +
`ALLOW FILTERING`;
if(req.params && validator.isUUID(req.params.idUser)) {
cassandra.execute(getHistory)
.then(ans => {
requestRace(timezone(ans.rows))
.then(aws => res.status(200).json({code:200, data:aws}))
.catch(err => console.log("error: ", err))
})
.catch(err => res.status(500).json({code: 500,data:{error: true,message: err}}))
}
}
'使用严格的'
import axios from "axios"
const route = `http://***/v1/inscription/`
async function requestRace(params) {
var newArr = new Array(), newObj = {}
for(let p in params) {
await axios.get(`${route}${params[p]['inscriptionid']}?apikey=pub_nLbIjlCWNKAdB_O3qgTaoQ`)
.then(res => {
newArr.push(creaJSON(params[p], res.data))
}).then(ok => {return ok})
.catch(err => console.log("error: ", err))
}
return newArr
}
function creaJSON(obj,subojb) {
obj['race'] = subojb[`data`]
return obj
}
module.exports = requestRace