Sequelize callback before save() is finished










0















here is my code:



//Models definition
var User = sequelize.define('user', ...);
var Address = sequelize.define('address', ...);
var Club = sequelize.define('club', ...);
//Club scopes
scopes: {
withUser:
include: [
model: User
]
,

//Models associations
User.hasOne(Address);
Club.hasOne(User);
Club.hasOne(Address);



//Main

//Create address
var addressToCreate = ;
if(body.address) addressToCreate.address = body.address;
if(body.city) addressToCreate.city = body.city;
if(body.zipCode) addressToCreate.zipCode = body.zipCode;

//Get user from db
var user = await User.findByPk(body.user);


var clubToCreate = name: body.name, phone: body.phone ;

//Persist Address in db
return Address.create(addressToCreate)
.then(address =>

//Persist club in db
return Club.create(clubToCreate)
.then(club =>

//Associate User and Address to Club
club.setAddress(address);
club.setUser(user);

//Save club with associated models
return club.save()
)
.then(club => Club.scope('withUser').findByPk(club.id))
.then(club => console.log(club); return club; )
)


In my db, table address contains userId and clubId and table user contains clubId;



This code seems to work to create and associate models. But the final club displayed by console.log shows user: null



However, in db there is the good row in table user with the good foreign key who reference the club id



My logs show that the request select (from Club.findByPk) is done before the update (from club.save). Like .then is executed before promise is resolved



Sry for my bad english, hope someone can help










share|improve this question






















  • Looks like it should work as expected. The only thing I can see that might prevent it doing so would be if club.save() is asynchronous but doesn't return a promise.

    – Roamer-1888
    Nov 14 '18 at 1:25















0















here is my code:



//Models definition
var User = sequelize.define('user', ...);
var Address = sequelize.define('address', ...);
var Club = sequelize.define('club', ...);
//Club scopes
scopes: {
withUser:
include: [
model: User
]
,

//Models associations
User.hasOne(Address);
Club.hasOne(User);
Club.hasOne(Address);



//Main

//Create address
var addressToCreate = ;
if(body.address) addressToCreate.address = body.address;
if(body.city) addressToCreate.city = body.city;
if(body.zipCode) addressToCreate.zipCode = body.zipCode;

//Get user from db
var user = await User.findByPk(body.user);


var clubToCreate = name: body.name, phone: body.phone ;

//Persist Address in db
return Address.create(addressToCreate)
.then(address =>

//Persist club in db
return Club.create(clubToCreate)
.then(club =>

//Associate User and Address to Club
club.setAddress(address);
club.setUser(user);

//Save club with associated models
return club.save()
)
.then(club => Club.scope('withUser').findByPk(club.id))
.then(club => console.log(club); return club; )
)


In my db, table address contains userId and clubId and table user contains clubId;



This code seems to work to create and associate models. But the final club displayed by console.log shows user: null



However, in db there is the good row in table user with the good foreign key who reference the club id



My logs show that the request select (from Club.findByPk) is done before the update (from club.save). Like .then is executed before promise is resolved



Sry for my bad english, hope someone can help










share|improve this question






















  • Looks like it should work as expected. The only thing I can see that might prevent it doing so would be if club.save() is asynchronous but doesn't return a promise.

    – Roamer-1888
    Nov 14 '18 at 1:25













0












0








0








here is my code:



//Models definition
var User = sequelize.define('user', ...);
var Address = sequelize.define('address', ...);
var Club = sequelize.define('club', ...);
//Club scopes
scopes: {
withUser:
include: [
model: User
]
,

//Models associations
User.hasOne(Address);
Club.hasOne(User);
Club.hasOne(Address);



//Main

//Create address
var addressToCreate = ;
if(body.address) addressToCreate.address = body.address;
if(body.city) addressToCreate.city = body.city;
if(body.zipCode) addressToCreate.zipCode = body.zipCode;

//Get user from db
var user = await User.findByPk(body.user);


var clubToCreate = name: body.name, phone: body.phone ;

//Persist Address in db
return Address.create(addressToCreate)
.then(address =>

//Persist club in db
return Club.create(clubToCreate)
.then(club =>

//Associate User and Address to Club
club.setAddress(address);
club.setUser(user);

//Save club with associated models
return club.save()
)
.then(club => Club.scope('withUser').findByPk(club.id))
.then(club => console.log(club); return club; )
)


In my db, table address contains userId and clubId and table user contains clubId;



This code seems to work to create and associate models. But the final club displayed by console.log shows user: null



However, in db there is the good row in table user with the good foreign key who reference the club id



My logs show that the request select (from Club.findByPk) is done before the update (from club.save). Like .then is executed before promise is resolved



Sry for my bad english, hope someone can help










share|improve this question














here is my code:



//Models definition
var User = sequelize.define('user', ...);
var Address = sequelize.define('address', ...);
var Club = sequelize.define('club', ...);
//Club scopes
scopes: {
withUser:
include: [
model: User
]
,

//Models associations
User.hasOne(Address);
Club.hasOne(User);
Club.hasOne(Address);



//Main

//Create address
var addressToCreate = ;
if(body.address) addressToCreate.address = body.address;
if(body.city) addressToCreate.city = body.city;
if(body.zipCode) addressToCreate.zipCode = body.zipCode;

//Get user from db
var user = await User.findByPk(body.user);


var clubToCreate = name: body.name, phone: body.phone ;

//Persist Address in db
return Address.create(addressToCreate)
.then(address =>

//Persist club in db
return Club.create(clubToCreate)
.then(club =>

//Associate User and Address to Club
club.setAddress(address);
club.setUser(user);

//Save club with associated models
return club.save()
)
.then(club => Club.scope('withUser').findByPk(club.id))
.then(club => console.log(club); return club; )
)


In my db, table address contains userId and clubId and table user contains clubId;



This code seems to work to create and associate models. But the final club displayed by console.log shows user: null



However, in db there is the good row in table user with the good foreign key who reference the club id



My logs show that the request select (from Club.findByPk) is done before the update (from club.save). Like .then is executed before promise is resolved



Sry for my bad english, hope someone can help







promise sequelize.js instance






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 12 '18 at 17:04









Timothy LE ROCHTimothy LE ROCH

63




63












  • Looks like it should work as expected. The only thing I can see that might prevent it doing so would be if club.save() is asynchronous but doesn't return a promise.

    – Roamer-1888
    Nov 14 '18 at 1:25

















  • Looks like it should work as expected. The only thing I can see that might prevent it doing so would be if club.save() is asynchronous but doesn't return a promise.

    – Roamer-1888
    Nov 14 '18 at 1:25
















Looks like it should work as expected. The only thing I can see that might prevent it doing so would be if club.save() is asynchronous but doesn't return a promise.

– Roamer-1888
Nov 14 '18 at 1:25





Looks like it should work as expected. The only thing I can see that might prevent it doing so would be if club.save() is asynchronous but doesn't return a promise.

– Roamer-1888
Nov 14 '18 at 1:25












1 Answer
1






active

oldest

votes


















0














You are using async/await but mixing it up with the older promise style based on your code that fetches Users. Below is a copy of your code in async/await style, although you may not need to refetch the club object, etc, so continue to debug.



const address = await Address.create(addressToCreate);
let club = await Club.create(clubToCreate);
console.log('created club', club);

club.setAddress(address);
club.setUser(user);
await club.save();
console.log('saved club', club);

club = await Club.scope('withUser').findByPk(club.id);
console.log('reloaded club', club);
return club;





share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53266885%2fsequelize-callback-before-save-is-finished%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You are using async/await but mixing it up with the older promise style based on your code that fetches Users. Below is a copy of your code in async/await style, although you may not need to refetch the club object, etc, so continue to debug.



    const address = await Address.create(addressToCreate);
    let club = await Club.create(clubToCreate);
    console.log('created club', club);

    club.setAddress(address);
    club.setUser(user);
    await club.save();
    console.log('saved club', club);

    club = await Club.scope('withUser').findByPk(club.id);
    console.log('reloaded club', club);
    return club;





    share|improve this answer



























      0














      You are using async/await but mixing it up with the older promise style based on your code that fetches Users. Below is a copy of your code in async/await style, although you may not need to refetch the club object, etc, so continue to debug.



      const address = await Address.create(addressToCreate);
      let club = await Club.create(clubToCreate);
      console.log('created club', club);

      club.setAddress(address);
      club.setUser(user);
      await club.save();
      console.log('saved club', club);

      club = await Club.scope('withUser').findByPk(club.id);
      console.log('reloaded club', club);
      return club;





      share|improve this answer

























        0












        0








        0







        You are using async/await but mixing it up with the older promise style based on your code that fetches Users. Below is a copy of your code in async/await style, although you may not need to refetch the club object, etc, so continue to debug.



        const address = await Address.create(addressToCreate);
        let club = await Club.create(clubToCreate);
        console.log('created club', club);

        club.setAddress(address);
        club.setUser(user);
        await club.save();
        console.log('saved club', club);

        club = await Club.scope('withUser').findByPk(club.id);
        console.log('reloaded club', club);
        return club;





        share|improve this answer













        You are using async/await but mixing it up with the older promise style based on your code that fetches Users. Below is a copy of your code in async/await style, although you may not need to refetch the club object, etc, so continue to debug.



        const address = await Address.create(addressToCreate);
        let club = await Club.create(clubToCreate);
        console.log('created club', club);

        club.setAddress(address);
        club.setUser(user);
        await club.save();
        console.log('saved club', club);

        club = await Club.scope('withUser').findByPk(club.id);
        console.log('reloaded club', club);
        return club;






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 '18 at 18:12









        doublesharpdoublesharp

        19.3k33659




        19.3k33659



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53266885%2fsequelize-callback-before-save-is-finished%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Use pre created SQLite database for Android project in kotlin

            Darth Vader #20

            Ondo