87 key: BlobKey,
88 data: Buffer | string,
89) {
90 return new Promise(async (resolve, reject) => { 91 const stream = store.createWriteStream(key, (error, metadata) => {
92 if (error) {
93 reject(error);
144
145 it("should get block number stream", async function () {
146 const current = await client.blockchain.getCurrentBlockNum();
147 await new Promise(async (resolve, reject) => {148 const stream = client.blockchain.getBlockNumberStream();
149 stream.on("data", (num) => {
150 assert(num >= current);
The new Promise
constructor accepts an executor
function as an argument, which has resolve
and reject
parameters that can be used to control the state of the created Promise.
For example:
const result = new Promise(function executor(resolve, reject) {
readFile('foo.txt', (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
The executor function can also be an async function
.
However, this is usually a mistake, for a few reasons:
Promise
constructor can only catch synchronous exceptions, and an async function never throws - it always returns a promise (which might get rejected though). And that return value is ignored, as the promise is waiting for resolve to be called.Promise
to reject. This could make it difficult to debug and handle some errors.await
, this is usually a sign that it is not actually necessary to use the new Promise constructor, or the scope of the new Promise
constructor can be reduced.const foo = new Promise(async (resolve, reject) => {
readFile('foo.txt', (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
const result = new Promise(async (resolve, reject) => {
resolve(await foo);
});
const foo = new Promise((resolve, reject) => {
readFile('foo.txt', function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
const result = Promise.resolve(foo);