簡體   English   中英

何時在Sequelize承諾中使用收益?

[英]When to use return in Sequelize promises?

我對Sequelize和Promises並不陌生,對於不熟悉Java腳本語言和JavaScript語言的人來說,這可能會有些混亂。 無論如何,我注意到在承諾的某些實現中使用了“返回”。 在其他實現中則不是。 例如:

 //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);
          })
        })
      })
    })
  })

此處:不使用它們。

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.`}))
      };

有人可以向我解釋“返回”的用法嗎? 由於第二個代碼有效,因此顯然沒有必要嗎? 那么我什么時候必須使用它? 謝謝!!

從技術上講,您詢問了箭頭功能

 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()); 

如您所見,我們在af1使用return語句,因為我們必須在返回值之前編寫另一個“邏輯”。 如果不這樣做,則可以避免使用return語句(它可以提高代碼的簡潔性和可讀性)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM