Have a Promise wait for a callback [duplicate] - javascript

This question already has answers here:
How do I convert an existing callback API to promises?
(24 answers)
Closed 7 years ago.
I have a plugin I'm writing for a framework that uses Promises throughout.
The plugin is expected to return a Promise to process the event, and anything the plugin does during processing is chained before returning the next event.
I think...
Anyway - I am also using an older library that is completely callback based - and the callback doesn't follow the standard convention of having callback(err,resp) as the last parameter.
How do I turn this:
var call = libary.Api(_this.config.url, function(response){return new Promise() {Do my actions with the response..}}, _this.config.api_key);
return BbPromise.try(call).then(evt);
Into a Promise that depends on the callback being processed?

Try this:
return (new BbPromise(function(resolve) {
libary.Api(_this.config.url, function(response) {
resolve(response);
}, _this.config.api_key);
})).then(evt);

Related

Is there an easier way to compose javascript promises reolution [duplicate]

This question already has answers here:
Wait for multiple promises to finish
(6 answers)
How do I access previous promise results in a .then() chain?
(17 answers)
How to return many Promises and wait for them all before doing other stuff
(6 answers)
Closed 2 years ago.
I have two Promises (let's say p and q) that will retrieve data when resolved, and I want to do something foo that needs the both data. It has a solution as coded below. But is there a more elegant one?
p.then(pData => {
q.then(qData => {
foo(pData,qData);
});
});
I was wondering something like follows (hypothetical function and):
p.and(q).then(dataArr => foo( ...dataArr ));
In the case there's no such way, is there anything in the promises concept that would disallow this construction?

Calling Promise.resolve() on *potentially* non-promise values [duplicate]

This question already has answers here:
How to handle functions that do not always return a promise?
(2 answers)
Closed 4 years ago.
I have a situation where I need to check if a function returns a promise, the problem is, its a browser implemented function and some browsers DO return a promise and some don't. I was checking: How do I tell if an object is a Promise?, to see how to check if a function returns a promise and it recommends using Promise.resolve(). But what exactly happens when you call Promise.resolve() on a non-promisified function?
I tried reading this, but i wasn't able to find an answer to the question exactly: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve
From the MDN documentation:
returns a Promise object that is resolved with the given value. If the value is a promise, that promise is returned; if the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable.
So yeah wrapping that returned value with Promise.resolve would take care of promisifying that value.
You can assign what the function returns to a variable and then evaluate that variable like so:
var obj = whateverFunction();
if(typeof obj.then === "function"){
// This is a promise because it has a then function
}
Although I suspect the answer using Promise.resolve might be better.

I can't access object inside array even though it exists [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
This method stores JSON objects retrieved from a firebase database to array scores.
function loadScoresToArray(){
databaseRef.orderByChild("Score").on("child_added", function (snap) {
scores.push(snap.val());
});
}
Run the above method and print content of scores
loadScoresToArray();
console.log(scores);
console.log(scores[0]);
output
As seen here, objects have correctly been added to scores.
But I can't retrieve them using index.
Reading similar questions like this I think this might be because when console.log(scores[0]); is called, the array is still empty. It has not been populated yet. This is just my guess.
How do I solve this? Is there a way to create a delay until the array is populated?
But I can't retrieve them using index.
That's because you're performing an asynchronous operation. Instead of waiting for the response, the execution continues immediately and the statement after the request call is execute.
How do I solve this? Is there a way to create a delay until the array
is populated?
No, don't use a delay. You can use a callback function.
function loadScoresToArray(callback){
databaseRef.orderByChild("Score").on("child_added", function (snap) {
scores.push(snap.val());
callback(scores);
});
}
loadScoresToArray(function(scores){
console.log(scores[0]);
});
Another solution is to use Promise constructor in order to perform an asynchronous operation.
function loadScoresToArray(){
return new Promise(function(resolve, reject){
databaseRef.orderByChild("Score").on("child_added", function (snap){
scores.push(snap.val());
resolve(scores);
});
});
}
loadScoresToArray().then(function(scores){
console.log(scores[0]);
});
Here are possible approaches in order to solve your problem.
Promises with async/await (ES2017+)
Callbacks
Promises with then() (ES2015+)

Passing a prototype method to a Promise's then method [duplicate]

This question already has answers here:
Object method with ES6 / Bluebird promises
(2 answers)
Closed 5 years ago.
I have a promisified method I called readFilePromise, that resolves to a Buffer object from fs' readFile method. When I execute the following line
return readFilePromise(filePath).then(Buffer.prototype.toString.call);
I get the following error:
TypeError: undefined is not a function
However, when I execute the block:
return readFilePromise(filePath).then((data) => {
return Buffer.prototype.toString.call(data);
});
I get no error and the code executes fine.
In my mind they should be the same. Am I missing something obvious?
node v6.10.1
Buffer.prototype.toString.call is just Function.prototype.call which calls this using first object as a context. In your first example this inside call call will be undefined.
You need to bind call to Buffer.prototype.toString like this Buffer.prototype.toString.call.bind(Buffer.prototype.toString).
return readFilePromise(filePath)
.then(Buffer.prototype.toString.call.bind(Buffer.prototype.toString))

calling a async function inside then [duplicate]

This question already has answers here:
Removing nested promises
(2 answers)
Closed 7 years ago.
I have a piece of code that looks like this:
func().then(function (result){
var a = func1(result);
func2(a).then(function(result1){
////
}
}
As you can see func returns a promise, and in then part we call another func1 which also returns a promise. Is it possible to chain the promise returned from func2 with the promise of then, and somehow get ride of the nested functions in the second then.
The return value inside a then() function is used as a promise value itself. So you can easily return the new promise and keep on chaining here:
func()
.then(function (result){
var a = func1(result);
return func2(a);
})
.then(function(result1){
////
})
See 2.2.7 and 2.3.2 of the Promise A+ Spec.

Categories

Resources