Catching errors in js promises [duplicate] - javascript

This question already has answers here:
Return value from a Promise constructor
(2 answers)
Closed 2 years ago.
I am relatively new to javascript and want to find out how the things here work.
I don't understand why does it output
testing.js:2 Uncaught (in promise) Oops instead of catching this error and handling it.
Everything works fine if I just type reject(..)
Here is the code:
let alex = new Promise((resolve,reject)=>{
return Promise.reject('Oops');
})
.then((r)=>console.log(r))
.catch((err)=>console.log(err));

That's because you should use the two arguments received in the callback (resolve and reject). As you said, it works when you use reject('Oops') instead of return Promise.reject('Oops'). It should look like this:
let alex = new Promise((resolve,reject)=>{
reject('Oops');
})
.then((r)=>console.log(r))
.catch((err)=>console.log(err));
You can read more about promises here

Related

Await fetch not working as expected in Javascript [duplicate]

This question already has answers here:
async/await implicitly returns promise?
(5 answers)
Async function returning promise, instead of value
(3 answers)
Closed 1 year ago.
Why output from code below is PromiseĀ {<pending>} instead of Response.
What I doing wrong? Also await fetch("https://...") not working.
function asynchronousFunction() {
return fetch("https://thatcopy.pw/catapi/rest/")
}
const mainFunction = async () => {
const result = await asynchronousFunction()
return result;
}
console.log(mainFunction())
You shouldn't think of Promises and async functions (which return Promises) as something you can use to return a value at top-level. It's usually a bad idea that comes from the imperative and synchronous programming mindset.
Use chaining instead, either move the console.log inside mainFunction, or write this:
asynchronousFunction()
.then(console.log)

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))

Have a Promise wait for a callback [duplicate]

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);

JavaScript - "this" doesn't work when calling Promises instead of functions [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
So, I recently had a pretty weird problem when developing a library, safe_children.
When I was writing the examples, I decided to try making it like this:
var child = new Child('otherFile.js', 3 * 60);
child.loadScript()
.then(child.spawn);
This code doesn't work. this points to something I couldn't find out. However, this piece of code works:
var child = new Child('otherFile.js', 3 * 60);
child.loadScript()
.then(function(){
child.spawn();
});
Anyone knows why? What is this in this context? Thanks!
Your issue here has nothing to do with promises.
You are passing in child.spawn, which is nothing more than a function. Your promise has no way to know that it belongs to child, so all it can do is call it. Therefore, this will most likely either be null, undefined, or the window object.
You can see the same behavior by doing:
var sp = child.spawn;
sp(); // <---- `this` is not `child` here
You can get around this by doing:
.then(child.spawn.bind(child));
or by doing what you've already done.

Javascript pointer to function [duplicate]

This question already has an answer here:
Illegal Invocation error when console.log passed in a function
(1 answer)
Closed 8 years ago.
Javascript is def not my main programming language I for practice I wanted to do something simple, at least i thought ;)
This is my code:
function Log () {}
Log.format = function (func, facility, text) {
func("hellow");
};
Log.debug = function(facility, text) {
Log.format(console.warn);
};
When I call Log.debug("we", "deb"); I get a Uncaught TypeError: Illegal invocation error. What am I doing wrong?
Depending on the browser, console methods can only be called in the context of console. Try Log.format(console.warn.bind(console));

Categories

Resources