获取 promise 的值并分配给变量 [英] Get the value of a promise and assign to variable
问题描述
utility.fetchInfo()
返回一个 Promise 对象.我需要能够获得这个 Promise 对象的值并将它的值分配给一个变量,然后我可以在我的代码中使用它.
utility.fetchInfo()
returns a Promise object. I need to be able to get the value of this Promise object and assign the value of it to a variable that I can then use later on in my code.
目前,我可以愉快地将 result
的值打印到控制台,但我需要能够将此值分配给 myVal
.到目前为止,我已经尝试了很多东西,但没有任何效果.
At the moment, I can happily print the value of result
to the console, but I need to be able to assign this value to myVal
. So far, I've tried a lot of things and nothing has worked.
var myVal = Utility.fetchInfo().then(result => console.log(result));
谢谢
推荐答案
@dhilt 所说的但在 promise 回调函数中做你的事情:
What @dhilt said but do your stuff inside the promise callback function:
utility.fetchInfo().then(result => {
doSomethingWith(result);
});
如果您使用的是最新版本的 Node 或 Babel,则使用 async/await:
Or use async/await if you are using a recent version of Node or Babel:
async function myFunction () {
var myVal = await utility.fetchInfo();
}
这篇关于获取 promise 的值并分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!