fs.writeFile in a promise, asynchronous-synchronous stuff

前端 未结 10 1556
清歌不尽
清歌不尽 2020-11-30 22:49

I need some help with my code. I\'m new at Node.js and have a lot of trouble with it.

What I\'m trying to do:

1) Fetch a .txt with Amazon products (ASINs) ;<

10条回答
  •  鱼传尺愫
    2020-11-30 23:32

    For easy to use asynchronous convert all callback to promise use some library like "bluebird" .

          .then(function(results) {
                    fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
                        if (err) {
                            console.log(err);
                        } else {
                            console.log("JSON saved");
                            return results;
                        }
                    })
    
    
                }).catch(function(err) {
                    console.log(err);
                });
    

    Try solution with promise (bluebird)

    var amazon = require('amazon-product-api');
    var fs = require('fs');
    var Promise = require('bluebird');
    
    var client = amazon.createClient({
        awsId: "XXX",
        awsSecret: "XXX",
        awsTag: "888"
    });
    
    
    var array = fs.readFileSync('./test.txt').toString().split('\n');
    Promise.map(array, function (ASIN) {
        client.itemLookup({
            domain: 'webservices.amazon.de',
            responseGroup: 'Large',
            idType: 'ASIN',
            itemId: ASIN
        }).then(function(results) {
            fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("JSON saved");
                    return results;
                }
            })
        }).catch(function(err) {
            console.log(err);
        });
    });
    

提交回复
热议问题