New promises are created using the Promise
constructor.
This constructor accepts a single argument: a function called the executor
.
It contains the code to initialize the promise.
The executor is passed two functions named resolve()
and reject()
as arguments.
The resolve()
function is called when the executor has finished successfully and the promise is ready to be resolved.
The reject()
function indicates that the executor has failed.
let fs = require("fs"); function readFile(filename) { return new Promise(function(resolve, reject) { // trigger the asynchronous operation fs.readFile(filename, { encoding: "utf8" }, function(err, contents) { // check for errors if (err) { reject(err);//w w w.ja va 2 s . c o m return; } // the read succeeded resolve(contents); }); }); } let promise = readFile("main.js"); // listen for both fulfillment and rejection promise.then(function(contents) { // fulfillment console.log(contents); }, function(err) { // rejection console.error(err.message); });
In this example, the fs.readFile()
asynchronous call is wrapped in a promise.
The executor either passes the error object to the reject()
function or passes the file contents to the resolve()
function.