简体   繁体   中英

When to use return in Sequelize promises?

I am new to Sequelize and Promises which can be slightly a bit confusing for someone who is not very familiar with them and the javaScript language. Anyway, I have noticed that in some implementation of promises, the "return" is used. In other implementations it is not. For example:

 //FILL JOIN TABLE FROM EXISTING DATA
  Blog.find({where: {id: '1'}}) .then(blog => {
    return Tag.find({where: {id: '1'}}).then(tag => {
      return blog.hasTag(tag).
      then(result => {
        // result would be false BECAUSE the blog.addTag is still not used yet
        console.log("3 RESULT IS"+ result);
        return blog.addTag(tag).
        then(() => {
          return blog.hasTag(tag).
          then(result => {
            // result would be true
            console.log("4 RESULT IS"+ result);
          })
        })
      })
    })
  })

And here: They are not used.

const tags = body.tags.map(tag => Tag.findOrCreate({ where: { name: tag }, defaults: { name: tag }})
                                        .spread((tag, created) => tag))

   User.findById(body.userId)    //We will check if the user who wants to create the blog actually exists
       .then(() => Blog.create(body))
       .then(blog => Promise.all(tags).then(storedTags => blog.addTags(storedTags)).then(() => blog/*blog now is associated with stored tags*/)) //Associate the tags to the blog
       .then(blog => Blog.findOne({ where: {id: blog.id}, include: [User, Tag]})) // We will find the blog we have just created and we will include the corresponding user and tags
       .then(blogWithAssociations => res.json(blogWithAssociations)) // we will show it
       .catch(err => res.status(400).json({ err: `User with id = [${body.userId}] doesn\'t exist.`}))
      };

Can someone please explain to me the use of "return"? It is obviously not necessary since the second code works? So when do I have to use it? Thank you!!

Technically, you asked about arrow function .

 const dummyData = { foo: "lorem" }; const af1 = () => dummyData; const af2 = () => { dummyData.foo = "bar"; return dummyData; }; const af3 = () => { foo: "bar" }; const af4 = () => ({ foo: "bar" }); console.log(af1()); console.log(af2()); console.log(af3()); // Be aware if you wanna return something's started with bracket console.log(af4()); 

As you see, we use return statement in af1 because we have to write another "logic" before return a value. If you don't do that, you can avoid using return statement (it could improve your code simplicity and readable).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM