我试图从API获取数据并在数组中的每个对象上设置fights属性。 API调用可以正常工作,但是无论我尝试使用多少种方法来设置fights属性,该调用都始终为空。
我最初将fights
属性设置为null
,这是一个空对象,一个数组。什么都没有。我还尝试只设置一个对象属性,而不是遍历每个对象,希望保持简单,可以让我看到损坏的地方。
var sherdog = require('sherdog');
const heavyweight = [
{ "name": "danielcormier", "link": "https://www.sherdog.com/fighter/Daniel-Cormier-52311", "fights": [] },
{ "name": "stipe miocic", "link": "https://www.sherdog.com/fighter/Stipe-Miocic-39537", "fights": [] },
{ "name": "francis ngannou", "link": "https://www.sherdog.com/fighter/Francis-Ngannou-152341", "fights": [] },
{
"name": "junior dos santos",
"link": "https://www.sherdog.com/fighter/Junior-dos-Santos-17272",
"fights": []
}
];
for (var i = 0; i < heavyweight.length; i++) {
sherdog.getFighter(heavyweight[i].link, function (data) {
heavyweight[i].fights = data['fights'];
});
}
//试着承诺
function delay(url) {
// `delay` returns a promise
return new Promise(function (resolve, reject) {
// Only `delay` is able to resolve or reject the promise
sherdog.getFighter(url, function (data) {
resolve(data);
});
});
}
delay(heavyweight[0].link)
.then(function (v) { // `delay` returns a promise
console.log(v); // Logs the value once it is resolved
heavyweight[0].fights = v; // still does not work
})
.catch(function (v) {
// Or do something else if it is rejected
console.log("Rejected");
});
console.log(heavyweight[0].fights);
//尝试过回调
function onComplete(a) {
heavyweight[0].fights = a.fights;
}
function getFive(whenDone) {
setTimeout(sherdog.getFighter(heavyweight[0].link, function (data) {
whenDone(data);
}), 100000);
}
期望heavyweight[I].fights
=从sherdog
调用传回的数据。
但是结果总是heavyweight[I].fights = []
我不明白我在想什么。我将不胜感激任何解释,以便将来可以理解此概念。