search

Home  >  Q&A  >  body text

javascript - About how to write promise

I’m not very familiar with how to write Promise. I hope I can encapsulate some common states of reject and resolve. How can I write it better?
And the following writeFile Is it better to write it directly as a normal function? Sorry for posting the long code, please help. . . . Thanks

PHPzPHPz2792 days ago644

reply all(1)I'll reply

  • 黄舟

    黄舟2017-05-19 10:33:14

    Asynchronous operations are best to require promise 或者 Generator 函数 或者是 asyncfunctions

    var readFile = function (fileName) {
      return new Promise(function (resolve, reject) {
        fs.readFile(fileName, function(error, data) {
          if (error) reject(error);
          resolve(data);
        });
      });
    };

    Jiang Zi is simpler! Then put all the data processing logic inside the calling then 或者 catch

    reply
    0
  • Cancelreply