承诺在cron工作

时间:2016-09-02 10:33:40

标签: javascript node.js mongodb promise

我尝试运行代码但没有成功。 只有第一个调用才能在节点开始时起作用。

这是我目前的代码:

const Product = require('../models/Product');
const Price = require('../models/Price');

const cron = require('node-cron');
const amazon = require('amazon-product-api');
const util = require('util');
const _ = require('underscore')
/**
 * Cron job
 * Tracking price
 */

exports.track = () => {

cron.schedule('* * * * *', () => {

    const client = amazon.createClient({
        awsId: process.env.AWS_ID,
        awsSecret: process.env.AWS_SECRET,
        assocId: process.env.AWS_TAG
    });

  Promise.all([Product.getAsin()])
    .then(([asin]) => {
      let listId = _.pluck(asin, '_id');
      let listAsin = _.pluck(asin, 'asin');
      if (asin.length === 0) {
        return
      }

      client.itemLookup({
          idType: 'ASIN',
          itemId: listAsin,
          domain: 'webservices.amazon.fr',
          responseGroup: 'ItemAttributes,OfferFull,SalesRank'
      }).then((results) => {
        for(i=0; i<listId.length; i++){
            results[i].id = listId[i];
        }
        for(res of results) {
          Price.addPrice({
            asin: res.ASIN[0],
            product: res.id,
            salePrice: res.Offers[0].Offer[0].OfferListing[0].Price[0].Amount[0],
          })
        }
        console.log(listId);
        Product.makeUpdate(listId);

      }).catch(function(err) {
          console.log(err);
          console.log(util.inspect(err, true, null));
      });
    })
    .catch((err) => {
      console.log(err);
    })
})
}

对MongoDB的请求是异步的。

产品

const mongoose = require('mongoose');
mongoose.Promise = Promise;
const _ = require('underscore');
const moment = require('moment');

const productSchema = new mongoose.Schema({
  name: String,
  domain: String,
  originUrl: { type: String, unique: true },
  check: { type: Number, default: 0 },
  ean: String,
  asin: String
}, { timestamps: true });

Object.assign(productSchema.statics, {
  getAsin() {
    return this.find(
      { updatedAt: { $lt: oneMin },
        asin: { $ne: null }
      }
    ).limit(10)
    .select({ asin: 1 })
    .exec()//.then((tuples) => _.pluck(tuples, 'asin'))
  },
  makeUpdate(id) {
    console.log('list des ID updated => ' + id);
    return this.update({ _id: { $in: id } }, { $inc : { "check": 1 } } , {multi: true}).exec();
  }
});

const Product = mongoose.model('Product', productSchema);

module.exports = Product;

const oneMin = moment().subtract(1, 'minutes').format();

此外,由于我对JavaScript和Node.js一般都是新手,所以我们将非常感谢任何最佳实践或一般提示! :)

0 个答案:

没有答案