在React中,我试图在返回数据后将变量设置为axios调用。 但是,当控制台事后记录变量时,它就是一个Promise。 如何从promise中获取值并将其设置为变量?
let fourPackProducts = axios.get('URL').then(response => {
return response.data })
console.log(fourPackProducts)
答案 0 :(得分:0)
由于fourPackProducts
是承诺,您可以控制记录承诺。该问题的另一部分是,由于promise是异步的,因此在promise响应通过之前调用控制台日志。要正确设置对变量的promise响应,请尝试以下操作:
let promiseResponse;
let fourPackProducts = axios.get('URL').then(response => {
promiseResponse = response.data;
console.log(promiseResponse);
return promiseResponse;
})
大概你想在之后对这个变量做一些事情,但是如果诺言尚未完成,那么变量将是undefined
。为了在将变量设置为承诺响应后使用该变量,您需要chain promises。
答案 1 :(得分:0)
你完全按照要求去做。如果你想要console.log
正确的数据,那么链接另一个,就像这样,
let promiseResponse = axios.get('URL')
.then(response => response.data)
.then( data => { console.log( data ); return data });
请记住,ajax请求是异步的,因此在不使用异步处理程序的ajax请求之后的代码将运行,编译器不会停止并等待请求完成