How can we use promise in node.js packages [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
When we write a module for node.js, we use callback functions. I learned promises in javascript and I want to use in node.js module. Can we use promises instead of callback functions ? if we can, how ?
note : via function in node module file ( you know exports.some_func ) , we do somethings and we can send back informations with callback . Can we use promise instead of that callback ?

Can we use promise instead of that callback ?
Yes, rather than accepting a callback in your exported function, you can just return a promise and make sure that promise is resolved/rejected with the proper value/reason when the async operation is done.
Here's an example:
Imagine you have a module interface for reading a file, then you can have that interface return a promise like this:
// myFileModule.js
const fs = require('fs');
module.exports.getFile = function(filename, options) {
return new Promise(function(resolve, reject) {
fs.readFile(filename, options, function(err, data) {
if (err) return reject(err);
resolve(data);
});
});
}
The caller would then use it like this:
const myFiles = require('myFileModule.js');
myFiles.getFile('temp.txt').then(function(data) {
// process data here
}, function(err) {
// got an error here
});

Related

How do I consume an asynchronous response twice [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm looking for best nodeJS practice to consume the result of an asynchronous operation in two places.
I currently have the following pseudo-code
async function doSomething() {
const something = await fetchSomething();
console.log("something", something); // (A)
}
function fetchSomething() {
const promise = fetch("http://example.com/something");
/* new code to update something will live here (B) */
return promise;
}
So far so good
I now need to do make a change to update something within fetchSomething() at the line new code will live here. The new code will be something like something.timestamp = new Date();
How can I access something within fetchSomething() and be sure that the update I make to something at (B) occurs before I log something at (A).
Just convert your fetchSomething to also be async:
async function doSomething() {
const something = await fetchSomething();
console.log("something", something); // (A)
}
async function fetchSomething() {
const something = await fetch("http://example.com/something");
/* new code to update something will live here (B) */
something.someOtherThing = 'updated something!';
return something;
}
Every async function returns a Promise so you can just await it again.

Javascript scope in promises [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How can I access to the user object in the promises callback ?
I try to bind it with no success.
const promises = User.find(req.user._id).exec();
promises.then(function (user) {
noAccessFunction().then(function (customer) {
// HERE
user.save();
});
});
Promises are not callbacks! Mutate it as if it were a chain of values. Maybe something like this:
const promises = User.find(req.user._id).exec();
promises.then(function (user) {
return myfunction().then(function (customer) {
return user.save();
});
});
Promises can also be flattened:
const promises = User.find(req.user._id).exec();
promises.then(function (user) {
return myfunction(user);
})
.then(function (customer) {
return customer.save();
});
In any case the code above is speculation since you have not provided enough information as to what you want to happen.

How to iterate an array synchronously using lodash, underscore or bluebird [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have an array that contains filenames at each index. I want to download those files one at a time (synchronously). I know about 'Async' module. But I want to know whether any functions in Lodash or Underscore or Bluebird library supports this functionality.
You can use bluebird's Promise.mapSeries:
var files = [
'file1',
'file2'
];
var result = Promise.mapSeries(files, function(file) {
return downloadFile(file); // << the return must be a promise
});
Depending on what you use to download file, you may have to build a promise or not.
Update 1
An exemple of a downloadFile() function using only nodejs:
var http = require('http');
var path = require('path');
var fs = require('fs');
function downloadFile(file) {
console.time('downloaded in');
var name = path.basename(file);
return new Promise(function (resolve, reject) {
http.get(file, function (res) {
res.on('data', function (chunk) {
fs.appendFileSync(name, chunk);
});
res.on('end', function () {
console.timeEnd('downloaded in');
resolve(name);
});
});
});
}
Update 2
As Gorgi Kosev suggested, building a chain of promises using a loop works too:
var p = Promise.resolve();
files.forEach(function(file) {
p = p.then(downloadFile.bind(null, file));
});
p.then(_ => console.log('done'));
A chain of promise will get you only the result of the last promise in the chain while mapSeries() gives you an array with the result of each promise.
using Bluebird, there is a situation similar to yours with an answer here:
How to chain a variable number of promises in Q, in order?
This seems like a decent solution but in my opinion much less readable and elegant as async.eachSeries(I know you said you don`t want the 'async' solution but maybe you can reconsider.

Define Promise As ES6 Class Method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Using ES6 syntax to define a class and its methods, how can I define a method as a Promise, without having to wrap it in a regular function that returns a promise? I want to do something like the following below:
class PromiseMethod {
promiseMethod = new Promise(function(resolve, reject) {
return resolve();
}
}
Promises are just an object returned from a function — whether it be a method or not doesn't matter. Try this:
class Something {
promiseMethod () {
return new Promise(...);
}
}
(new Something).promiseMethod().then(...)
But maybe you wanted to not have to call the method and be able to use the Promise methods directly? In this case, it's not a method, it's a property:
class Something {
constructor () {
this.promiseProperty = new Promise(...);
}
}
(new Something).promiseProperty.then(...);

Can I do a "lazy" promise with Bluebird.js? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want a construct similar to promise that waits until then is called before it runs. That is, if I never actually call then, the promise will never run.
Is this possible?
Make a function which creates and returns a promise on first invocation, but returns the same promise on each subsequent invocation:
function getResults() {
if (getResults.results) return getResults.results;
getResults.results = $.ajax(...); # or where ever your promise is being built
return getResults.results;
}
Promises don't work in such a way that they could support lazy loading. Promises are created by asynchronous code in order to communicate a result. Until the async code has been invoked, there simply is no promise.
You could certainly write a promise-like object which did lazy invocation, but code that generated these promises would be very different:
// Accepts the promise-returning function as an argument
LazyPromise = function (fn) {
this.promise = null;
this.fn = fn
}
LazyPromise.prototype.then = function () {
this.promise = this.promise || fn();
this.promise.then.apply(this.promise, arguments)
}
// Instead of this...
var promise = fn();
// You'd use this:
var promise = new LazyPromise(fn);
It's better in this uncommon use to make the actual creation of the promise lazy (as in either above example), rather than trying to make promises themselves responsible for lazy-evaluation.

Categories

Resources