繁体   English   中英

化解链内承诺

[英]Resolve promise inside chain

我在解决链内的承诺时遇到了一些麻烦。 在下面的JSBin中,您可以看到我拥有的代码(NodeJS和mongo)。 如何从链的2个级别返回数据? 这是代码和JSBIN

function test(url) {
  return new Promise((resolve, reject) => {
  return scrapeIt({
    url: url,
    headers: { 'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36' }
  }, {
      urls: {
        listItem: '#list',
        data: {
          url: {
            selector: "span[data-label='url']"
          }
        }
      },
      currentPage: {
        selector: 'span.current',
        convert: x => parseInt(x)
      },
      pages: {
        selector: 'span.pages',
        convert: x => parseInt(x)
      }
    }).then(({ data, response }) => {
      return MongoClient.connect(config.db.serverUrl, function (err, db) {
        var dbo = db.db(config.db.name)
        var urlsToInsert = data.urls

        return dbo.collection(config.db.collection).find({ 'url': { '$in': data.urls } }, { projection: { _id: 0 } }).toArray(function (err, res) {
          if (res && res.length > 0) {
            // Exclude properties already in DB
            urlsToInsert = urlsToInsert.filter(x => !res.some(y => x.url == y.url))
            if (urlsToInsert && urlsToInsert.length > 0)
              return dbo.collection(config.db.collection).insertMany(urlsToInsert, function (err, res) {
                console.log("Number of documents inserted: " + res.insertedCount)

                db.close()
                return urlsToInsert
              })
          }
        })
      })
    })
})
}

test('https://www.google.com').then(({ data, response }) => {
  console.log(data)
}).catch((error) => {
  console.log(error)
})

JSBin片段

更新1

我的实际代码更长,因此我取出了很多使问题有意义的代码。 我修复了urlsToInsert为null的问题。 现在还返回urlsToInsert。

我试图重写最后一部分,但是您的代码无法正常工作,因为您将urlsToInsert设置为一个空数组,然后对其进行过滤。

您将返回从未在代码中的任何地方定义的propertiesToInsert

.then(
  ({ data, response }) =>
    new Promise(
      (resolve,reject)=>
        MongoClient.connect(config.db.serverUrl,(err, db) =>
          (err, db) =>
            (err)
              ? reject(err)
              : resolve(db.db(config.db.name))
        )
    )
).then(
  dbo=>
    new Promise(
      (resolve,reject)=>
        dbo.collection(config.db.collection).find(
          { 'url': { '$in': data.urls } },
          { projection: { _id: 0 } }
        ).toArray((err, res) =>
          (err)
            ? reject(err)
            : resolve(res)
        )
    ).then(
      res=>{
        var urlsToInsert = [];
        if (res && res.length > 0) {
          // Exclude properties already in DB THIS MAKES NO SENSE, FILTERING AN EMPTY ARRAY
          urlsToInsert = urlsToInsert.filter(x => !res.some(y => x.url == y.url))
          if (urlsToInsert && urlsToInsert.length > 0) {
            return new Promise(
              (resolve,reject)=>
                dbo.collection(config.db.collection).insertMany(urlsToInsert, function (err, res) {
                  if(err){reject(err);}//this never happens anyway
                  console.log("Number of documents inserted: " + res.insertedCount);    
                  db.close();
                  //what are you returning here?
                  resolve(propertiesToInsert)
                })
            )
          } 
          return [];//what to return if there are no urls to insert (always because you're filtering empty array)
        }
      }
    )
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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