获取 promise 的值并分配给变量 [英] Get the value of a promise and assign to variable

查看:60
本文介绍了获取 promise 的值并分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆