JS获取Promise对象里面的值问题

 

JS获取Promise对象里面的值

1、以下代码返回值为:

	const res = getTaskItems({});
  if (res.code === 0) {
  	this.taskItem = res.data;
  }

2、使用一下代码即可获取data里面的值

  getTaskItems({}).then(res => {
    console.log(res.data);
  })

 

获取Promise{<pending>}的值

问题

我使用如下代码

let lyric = getLyric(this.$store.state.songId);
console.log(lyric)

获取到的结果:

如果直接console.log(lyric.data),会输出undefined

解决

let lyric = getLyric(this.$store.state.songId);
let a = lyric.then((res)=>{
  console.log(res.data)
});

 

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程宝库

JavaScript 中的 this 关键字引用了所在函数正在被调用时的对象。在不同的上下文中,this 的指向会发生变化。可以通过 call, apply, bind ...