Посмотрите на свой код так:
function checkPoints(id){
let points;
// make a new variable, nothing is assigned so give it undefined
http.getJSON('MY_API_URL' + id).then(...)
// Promise? handle later, go to next line.
return points;
// return undefined
}
Очки всегда будут undefined
. Вы присваиваете point
внутри http.getJSON
then
, поэтому даже если бы эта функция была синхронной, point
внешней области видимости был бы undefined
. Редактировать Вы бы не использовали then
, если бы функция была синхронной, а point
был бы изменен, мой плохой!
Вы можете изменить свой код так, чтобы checkPoints()
возвращал Promise, что гарантируетвам данные были возвращены.
function checkPoints(id){
return http.getJSON('MY_API_URL' + id).then(
function (response) {
return response[0].point; <-- return the response[0].point
},
function(error) {
console.log("Server err.");
})
}
или с функцией стрелки
const checkPoints = (id) => http.getJSON(`MY_API_URL${id}`)
.then(response => response[0].point)
.catch(error => console.log("Server err."))
И в вашей функции вы можете использовать async / await:
...
// V checkLengtht has to be an async function, otherwise it can't use await
CheckLenght: async function(id) {
var status = false;
var response = await checkPoints(id);
if(response > 10){
status true;
} else {
status false;
}
return status;
}
Youможете переписать ваш код следующим образом:
CheckLenght: async function(id) {
const points = await checkPoints(id);
return (points > 10) // return true if points > 10, else return false. Note that this function's return will be wrapped in Promise.
}
Обратите внимание, что CheckLength теперь является асинхронной функцией, то есть возвращает Promise;когда вы используете его, вы должны использовать await
или .then()
.
Вы также можете полностью отказаться от async / await:
...
CheckLenght: id => checkPoints(id).then(points => points > 10);
Как использовать async/ await
Добавление async
перед объявлением функции приводит к возвращению Promise.
const add = (a, b) => a + b
add(1, 2) // 3
const add = async (a, b) => a + b
add(1, 2) // Promise(...)
add(1, 2).then(res => console.log(res)) // 3
await
может использоваться внутри функции async
для получения ответа Promise.
const main = async () => {
const res = await add(1, 2)
console.log(res)
}
main() // 3