fs.writeFile in a promise, asynchronous-synchronous stuff

前端 未结 10 1563
清歌不尽
清歌不尽 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:35

    Because fs.writefile is a traditional asynchronous callback - you need to follow the promise spec and return a new promise wrapping it with a resolve and rejection handler like so:

    return new Promise(function(resolve, reject) {
        fs.writeFile("", data, '', function(err) {
            if (err) reject(err);
            else resolve(data);
        });
    });
    

    So in your code you would use it like so right after your call to .then():

     .then(function(results) {
        return new Promise(function(resolve, reject) {
                fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
                   if (err) reject(err);
                   else resolve(data);
                });
        });
      }).then(function(results) {
           console.log("results here: " + results)
      }).catch(function(err) {
           console.log("error here: " + err);
      });
    

提交回复
热议问题