【问题标题】:NodeJS - Update an Object with returned PromiseNodeJS - 使用返回的 Promise 更新对象
【发布时间】:2018-11-09 03:09:02
【问题描述】:

我一直在努力兑现承诺。无论我读了多少这个问题的措辞,我都无法解决它。

我有一个实验室类/函数,它具有已部署(布尔值)的属性。我想检查一下是否部署了实验室。我已经有一个实验室对象,因此我调用了 lab.isDeployed()。但是,当它返回时 - 它返回 true 或 false 但是由于此异步“功能”,我不再可以访问原始实验室对象。

function lab(id) {
    this.deployed = null; //This is the property.
    this.isDeployed = function(){
        return isLabDeployed(this.id, this.userID).then(function(data){ 
            return data; //Where Data is a query to determine if its deployed.
        });
}

这是从另一个方法调用的。

l.isDeployed().then(function(data){
    expect(data).to.be.equal(false);;
}); 

我应该将实验室对象传回原始方法吗? IE 而不是返回上面的数据,我应该更新已部署的属性并返回这个吗?还是有其他方法?我试图限制代码,因为我希望得到解释。

【问题讨论】:

  • 你可以使用var proValue = await isLabDeployed(this.id, this.userID)
  • 基本上你是在做异步同步吗?我觉得这违背了异步的目的/意义?

标签: javascript node.js asynchronous


【解决方案1】:

尝试做这样的事情:

this.isDeployed() = function() {
    return new Promise(
        (resolve, reject) => {
            isLabDeployed(this.id, this.userID)
                .then((data) => {
                    resolve(data);
                });
        }
    );

然后,您可以调用 isDeployed 函数作为承诺。

this.isDeployed()
    .then((data) => {
        // this is where you use your data.
    });

否则,您可能需要使用 async/await

const data = await this.isDeployed()

基本上,您希望解决作为承诺获得的数据。你甚至可以做一些简单的事情,比如。

this.isDeployed() = isLabDeployed(this.id, this.userId)

【讨论】:

  • 删除 Promise 构造函数反模式。代码就是this.isDeployed = function () { return isLabDeployed(this.id, this.userID) }
  • @DanD。非常感谢您的帮助,但是我想我不完全理解这不会返回承诺并给我留下原始问题?如果 isLabDeployed 返回一个承诺 - 当我从调用 isLabDeployed 返回时,我是否仍然会发现实验室的属性未定义?
  • 不出所料——你们都是对的,但我不明白为什么会这样......
  • 如果您从 Promise 解析器内部使用实验室,您可能会遇到范围界定问题。否则,我不明白为什么您的实验室会变得不确定。尝试使用箭头符号l.isDeployed().then((data) => {expect(data).to.be.equal(false);});
【解决方案2】:

您仍然可以访问l 对象

l.isDeployed().then(function(data){
    expect(data).to.be.equal(false);
    console.log(l.deployed) // lab object still accessible here
});

或者使用异步/等待:

const data = await l.isDeployed()
console.log(l.deployed) // lab object still accessible here

【讨论】:

  • 我当时的理解是我仍然可以访问 l 但它返回为未定义......我认为范围将包括“父”(我不认为那是正确的词)?
猜你喜欢
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
  • 2019-11-10
  • 2019-06-30
  • 2019-03-28
  • 2016-05-18
相关资源
最近更新 更多