保留 SailsJs 服务属性值

Retaining SailsJs Service property value

本文关键字:属性 服务 SailsJs 保留      更新时间:2023-12-20

我有如下服务:

一些服务.js

module.exports = {
    property:null,
    foo:function(){
       User.destroy({user_email:user.user_email}).exec(function(error,users){   
           this.property='somevalue'
       });
    }
}

当我像下面这样调用此服务时,它不会保留property变量的值。

SomeService.foo();
console.log(SomeService.property) //returns null

如何使用 Sails 服务保留property值?我如何像上课一样使用它?也许这更像是一个JavaScript问题,而不是Sails。我知道该对象与我使用它的方式不同,但是有没有办法让我可以将相同的对象用于服务?

更新

:我已经更新foo,我认为在这种情况下this是指destroy构造而不是服务。

很明显,由于该功能foo,您正在null 正在调用异步方法

foo:function(){
    //the below functions is asynchronous so it is being pushed to event queue.
    //and setting this.property='someValue' becomes asynchronous.
    User.destroy({user_email:user.user_email}).exec(function(error,users){
        this.property='somevalue'
    });
};

所以在打电话时:

SomeService.foo();//this is asynchronous so does not block next executions.
console.log(SomeService.property)//this is not blocked by above call.

如果你想测试到底发生了什么。运行以下命令。

module.exports = {
    property:null,
    foo:function(){
        User.destroy({user_email:user.user_email}).exec(function(error,users){
            SomeService.property='somevalue';
            console.log("Am i executed first???? Oh no I am the last among them");
        });
    }
};

而这:

SomeService.foo();
console.log(SomeService.property);
for(var i=2;i<10;i++)
    console.log("I am called at number:",i);

所以我想你明白了它发生的原因。