2017-02-18 45 views
0

我有这样的代码时:试图数据推到我的数组为保证这不保存数据

let splatshArtData = []; 
splatshArt.getSplatchArt(participants[i].championId).then((splatshArtUrl) => { 
    splatshArtData.push(splatshArtUrl);     
}); 
console.log(splatshArtData); 

我要添加“splatshArtUrl”我的阵列,但是这不工作,当我尝试打印数据,这不会打印什么,我不知道该怎么做,任何想法?异步函数getSplatchArt解决它的承诺之后

let splatshArtData = []; 
splatshArt.getSplatchArt(participants[i].championId).then((splatshArtUrl) => { 
    splatshArtData.push(splatshArtUrl); 
    console.log(splatshArtData);     
}); 

的功能then运行里面,所以它运行的console.log项目被添加到阵列之前:

+0

'.save'方法是什么? –

+0

@ Alexandru-IonutMihai哦,没什么,脏的代码:p –

+1

将'console.log(splatshArtData);'移到'.then()'块中,它会起作用。你的函数调用是异步的,但你认为它是同步的,因此是错误。 –

回答

0

试试这个。

+0

这不是真的正确。当然这是有效的,但'.then()'中的函数显然不会在异步函数*之后运行。它会在'getSplatchArt'返回的许诺得到解决时运行,其中*可能恰好在之后,但也可能在10分钟后。 –

+0

我不想迷惑他,因为他似乎不明白承诺会做什么。 –

+0

那么,你应该清楚它的工作原理,因为你现在所说的答案是不正确的。 –

0

你在这里面临的问题是getSplatchArt返回一个承诺,并承诺需要时间来解决。因此,您不能保证splatshArtData.push(splatshArtUrl);将在console.log之前运行。

解决方案是将所有需要从promise中返回的数据的逻辑移到promise回调中。这当然可以包括对其他功能的调用。

// function to process the splashArtData - will be called from the promise 
// when the promise is resolved. 
function processSplashArt(data) { 
    // this will now print as you are expecting 
    console.log(data); 
} 

let splatshArtData = []; 

splatshArt.getSplatchArt(participants[i].championId).then((splatshArtUrl) => { 
    splatshArtData.push(splatshArtUrl);  

    // pass the splashArtData to the callback function - it's now ready 
    processSplashArt(slashArtData);   
}); 
0

JavaScript是同步的,因此每行代码都会一个接一个执行。

如果我们注释行号代码像下面

1. let splatshArtData = []; 
2. splatshArt.getSplatchArt(participants[i].championId).then((splatshArtUrl) => { 
3.  splatshArtData.push(splatshArtUrl);     
    }); 
4. console.log(splatshArtData); 

你假设它会在1,2,3,4的顺序运行,而在现实中,它会在顺序运行1,2,4,3为什么?因为JavaScript是同步的,并且第2行中的函数是异步的,这意味着在继续之前您必须等待。如果您没有将splatshArtData变量设为空数组,因为尚未提取数据。

如果你想返回提取的数据并在另一个函数中使用它,你不应该混合它将回调建议在另一个答案,而是诺言和使用从获取函数的解析值数据。

function getSplatshArt() { 
    let splatshArtData = []; 

    //Return a promise 
    return splatshArt.getSplatchArt(participants[i].championId).then((splatshArtUrl) => { 
     console.log(splatshArtData); //this will log out the data 
     splatshArtData.push(splatshArtUrl); 
     return splatshArtData; //this will be the resolved value from the promise 
    }); 
} 

//Call the function and access the resolved data in the .then() block 
getSplatshArt() 
    .then(data => { 
     console.log(data); //this is the data returned from the getSplatshArt function 
    }); 

看你的代码,我开始觉得你是遍历ID的数组的印象,如果你想一次取多个值,这不会工作,因为你必须处理多个承诺。但那是另一个问题,我想你应该在询问这个问题之前,先对自己的问题做更多的研究。