【问题标题】:Assigning result of a resolved Promise to a variable将已解决的 Promise 的结果分配给变量
【发布时间】:2021-06-19 17:22:08
【问题描述】:

我有一个服务,它有一个返回 Promise 的函数;

service.getStuff(); // returns a Promise of an array; I'm interested in the field 'cool stuff'

在单独的服务中,我想获取已解决的承诺的结果并将其分配给全局变量,如下所示:

scope.coolStuff = {resolved value of service.getStuff()['cool stuff']}

我试过这样做:

service.getStuff()
    .then(function(stuff) {
        scope.stuff = stuff['cool stuff'];
    });

但是,console.logging scope.stuff 稍后显示该值未定义。我在这里想念什么?提前致谢!

【问题讨论】:

  • 确认一下,stuff的类型是数组而不是对象?
  • 是的,所以service.getStuff() 返回一个承诺,当解决时,它是一个数组
  • 根据这篇文章:stackoverflow.com/questions/41091818/… 这是不允许的,但我想确认/看看还有哪些其他选项
  • 你能console.log(stuff) 告诉我你得到了什么吗?
  • service.getStuff() .then(function(stuff) { scope.stuff = stuff['cool stuff']; console.log(scope.stuff); });控制台.log(范围.stuff); /** * 打印:* undefined * true **/

标签: javascript angular promise pg-promise


【解决方案1】:

关于 Promise,您需要了解的是,它们正在包装异步发生的代码。也就是说,在程序的正常控制流程之外。在 Promise 上设置 延续函数 作为对 then() 的回调来注册代码以在 Promise 解析如下之后 运行非常简单:

function doSomething(result) {
// some code
}

myPromise.then(doSomething).then((result) => {
 doAnotherThingInAnAnonymousFunction();
 console.log(result);
 console.log('this happens after doSomething()');
});

可能需要一点时间来习惯以这种方式使用延续函数。如果你想跳到更熟悉的地方,你可以将你的代码包装在一个 async/await 模式中,它看起来就像你的异步代码一样工作(但相信我,它使用 Promises 和引擎盖下的延续函数)。

async function doAsyncStuff() {
  const result = await service.getStuff();
  scope.stuff = result['mine'];
  console.log(scope.stuff); // this is up to date because of the await above
}

继续阅读以了解更多信息:https://www.oreilly.com/library/view/you-dont-know/9781491905241/ch04.html

这些东西对于 JS 开发来说相当重要,我建议你花一些时间来研究它。

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多