Modern JS/Promise newbie here. I'm having trouble finding the answer to a simple question, despite the overwhelming amount of content on this subject.
I believe I have a decent understanding of JS Promises (thanks to various sources, including mdn and https://spin.atomicobject.com/2016/02/16/how-javascript-promises-work/)
I have consumed and produced Promises regularly in their simplest form, however I keep stumbling on methods in my inherited projects with the following pattern:
const doAsyncOp = () =>
$http.get(uri)
.then(
value => value,
reject => //...
);
My big question is: What happens when you simply return a value from your success handler? I need to consume this method, and need access to 'value' in the client code. Is this technically unhandled? Should I rewrite the implementation?
My big question is: What happens when you simply return a value from your success handler?
When you return a value from a .then() handler, that value becomes the resolved value of the parent promise chain: So, in this code:
// utility function that returns a promise that resolves after a delay
function delay(t, v) {
return new Promise(resolve => {
setTimeout(resolve.bind(null, v), t);
});
}
function test() {
return delay(100, 5).then(val => {
// this return value becomes the resolved value of the promise chain
// that is returned from this function
return 10;
});
}
test().then(result => {
// logs 10
console.log(result);
});
When you run it, it will log 10 because of the return 10 in the .then() handler.
There are four possibilities from a .then() handler:
Return a regular value such as return 10 or return val. That value becomes the resolved value of the promise chain. If no value is returned (which in Javascript means the return value is undefined), then the resolved value of the promise chain is undefined.
Return a promise that ultimately resolves or is already resolved. This promise is added to the chain and the promise chain takes on the resolved value of that promise.
Return a promise that ultimately rejects or is already rejected. This promise is added to the chain and the promise chain takes on the rejected reason of the returned promise.
Throw an exception. If an exception is thrown inside the .then() handler, then the .then() infrastructure will catch it and turn the promise chain into a rejected state with the reject reason set to the value that is thrown. So, if you do throw new Error("User not found") inside a .then() handler, then that promise chain will be rejected with that error object as the reject reason.
In your specific code:
const doAsyncOp = () =>
$http.get(uri)
.then(
value => value,
reject => //...
);
There is no reason for the value => value. value is already the resolved value of the promise, you do not need to set it again.
And since the fat arrow function automatically returns any single statement, you're already returning the promise from $http.get().then() in your doAsyncOp() function. So, you can just do:
const doAsyncOp = () => $http.get(uri);
doAsyncOp().then(result => {
// handle the result here
}).catch(err => {
// handle error here
});
To get this to the client code, just return the promise from your function:
const doAsyncOp = () => $http.get(uri)
then in your client you can use:
doAsyncOp()
.then(value => {
// use value
}
.catch(err => { /* error */ }
I think you can use async and await for the resolved values.
function delay(t, v) {
return new Promise(resolve => {
setTimeout(resolve.bind(null, v), t);
});
}
async function(){
await myData = delay(1000, 1000);
console.log(myData);
}
Related
When I write an async function it usually returns a promise:
export const myPromiseFunction = async (params) => {
// some logic
return Promise.resolve('resolved-value');
});
But I was wondering if it would be a mistake if this function would not return a promise, so for example:
export const myPromiseFunction = async (params) => {
// some logic
params.map(async (param) => {
await printParam(param);
async function printParam(par) {
// do some other stuff
Printer.print(par);
});
});
});
export class Printer {
public static async print(par) {console.log(par);} // I know it could not be async, but for the sake lets suppose it does
}
Is this a mistake / bad practice ? Or can we find a scenario when this will be valid and desirable ?
All async functions automatically return Promises. If you declare a function as async, it will return a Promise, even if your only return value is a simple value like a string or number. If you don't return explicitly, your async function will still return a Promise with a value of undefined.
In fact, it is more common for the body of an async function to return a simple value rather than a promise; the assumption is that your function is async because you await the promises you consume within it. As a consequence, even if you return the value 5, the return value is a Promise (that resolves to 5) representing the potential delay that comes from any await expressions in the function.
You don't have to return a Promise object explicitly in your async function, and it is redundant to do so if you're just wrapping a simple value like 'resolved-value'. Conversely, you can make a normal function behave like an async function if you always return a Promise (potentially with Promise.resolve) and you never synchronously throw an error within it.
async function myFunction() {
makeSomeCall(); // Happens immediately.
await someOtherPromise(); // myFunction returns a Promise
// before someOtherPromise resolves; if it
// does without error, the returned Promise
return 5; // resolves to 5.
}
/** Behaves the same as the above function. */
function myFunctionButNotAsync() {
try {
makeSomeCall();
// If you didn't have someOtherPromise() to wait for here, then
// this is where Promise.resolve(5) would be useful to return.
return someOtherPromise().then(() => 5);
} catch (e) {
return Promise.reject(e);
}
}
All that said, you may have occasion to explicitly return a Promise object (such as one produced by Promise.all or a separate Promise-returning function), which then observes rules similar to what Promise.resolve() observes: If the object you return from an async function is a Promise, or has a then function, then the automatic Promise the async function returns will wait for the specific Promise or Promise-like object you pass back with return.
async function myFunction() {
makeSomeCall(); // Happens immediately.
await anythingElse(); // You can still await other things.
return someOtherPromise(); // The promise myFunction returns will take
// the same outcome as the Promise that
// someOtherPromise() returns.
}
In a related sense, this is why return await is seen as redundant, though as described it does make a difference for the stack traces that you see if the wrapped promise is rejected.
Short answer: no, an async function doesn't have to returns a Promise. Actually, generally you wouldn't return a Promise object (unless you're chaining asynchronous events).
What async and await do is wait for a response from something that returns a Promise.
You first code example actually returns a resolved Promise. But what happens if the Promise isn't resolved properly ?
It's best to call a function that returns a Promise from another async function:
function getRequestResult() {
return new Promise(resolve => {
setTimeout(() => {
resolve('request sent');
}, 2000);
});
}
async function sendMyRequest() {
console.log('Sending request');
const result = await getRequestResult();
console.log(result);
// expected output: "resolved"
}
You can send rejections/errors within getRequestResult() that way, and also manage how these errors will be managed by the call in sendMyRequest() (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await).
Background
The TC39 proposal-promise-finally, which is now part of the ES2018 specification, lists the following key points also paraphrased on MDN to describe exactly what the method does.
promise.finally(func) is similar to promise.then(func, func), but is different in a few critical ways:
When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it
A finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. This use case is for precisely when you do not care about the rejection reason, or the fulfillment value, and so there's no need to provide it.
Unlike Promise.resolve(2).then(() => {}, () => {}) (which will be resolved with undefined), Promise.resolve(2).finally(() => {}) will be resolved with 2.
Similarly, unlike Promise.reject(3).then(() => {}, () => {}) (which will be resolved with undefined), Promise.reject(3).finally(() => {}) will be rejected with 3.
However, please note: a throw (or returning a rejected promise) in the finally callback will reject the new promise with that rejection reason.
In other words, a concise polyfill using a Promise implementation that conforms to the Promises/A+ specification is as follows (based on the answers by #Bergi and #PatrickRoberts).
Promise.prototype.finally = {
finally (fn) {
const onFulfilled = () => this;
const onFinally = () => Promise.resolve(fn()).then(onFulfilled);
return this.then(onFinally, onFinally);
}
}.finally;
If we contrast a promise chain using Promise#then and Promise#finally with an async function containing a try...finally block, we can determine some key differences, which are also mentioned but not elaborated here.
const completions = {
return (label) { return `return from ${label}`; },
throw (label) { throw `throw from ${label}`; }
};
function promise (tryBlock, finallyBlock) {
return Promise.resolve()
.then(() => completions[tryBlock]('try'))
.finally(() => completions[finallyBlock]('finally'));
}
async function async (tryBlock, finallyBlock) {
try { return completions[tryBlock]('try'); }
finally { return completions[finallyBlock]('finally'); }
}
async function test (tryBlock, finallyBlock) {
const onSettled = fn => result => console.log(`${fn}() settled with '${result}'`);
const promiseSettled = onSettled('promise');
const asyncSettled = onSettled('async');
console.log(`testing try ${tryBlock} finally ${finallyBlock}`);
await promise(tryBlock, finallyBlock).then(promiseSettled, promiseSettled);
await async(tryBlock, finallyBlock).then(asyncSettled, asyncSettled);
}
[['return', 'return'], ['return', 'throw'], ['throw', 'return'], ['throw', 'throw']]
.reduce((p, args) => p.then(() => test(...args)), Promise.resolve());
.as-console-wrapper{max-height:100%!important}
This demonstrates that the semantics for the settled state of the resulting promise differ from the analog try...finally block.
Question
What was the reason for not implementing Promise#finally such that a special case for a callback that resolved to undefined using the promise resolution procedure was the only condition for which a resolved finally() re-adopted the state of the original promise?
Using the following polyfill, the behaviors would match more closely with the analog try...finally block, except for when the finally block contains an explicit return; or return undefined; statement.
Promise.prototype.finally = {
finally (fn) {
const onFulfilled = value => value === undefined ? this : value;
const onFinally = () => Promise.resolve(fn()).then(onFulfilled);
return this.then(onFinally, onFinally);
}
}.finally;
As a follow-up question, in case the consensus is that the current specification is more palatable than the suggestion above, are there any canonical usages of Promise#finally that would be more cumbersome to write if it used this instead?
This demonstrates that the semantics for the settled state of the resulting promise differ from the analogue try...finally block.
Not really, you just used the "wrong" try/finally syntax in your comparison. Run it again with
async function async (tryBlock, finallyBlock) {
try { return completions[tryBlock]('try'); }
finally { completions[finallyBlock]('finally'); }
// ^^^^^^ no `return` here
}
and you will see that it is equivalent to .finally().
What was the reason for not implementing Promise#finally such that a special case for a callback that resolved to undefined using the promise resolution procedure was the only condition for which a resolved finally() re-adopted the state of the original promise?
The proposal gives the following rationale: "Promise#finally will not be able to modify the return value […] - since there is no way to distinguish between a “normal completion” and an early return undefined, the parallel with syntactic finally must have a slight consistency gap."
To give an explicit example, with the try/catch syntax there is a semantic difference between
finally {
}
and
finally {
return undefined;
}
but the promise method cannot be implemented to distinguish between
.finally(() => {
})
and
.finally(() => {
return undefined;
})
And no, it simply made no sense to introduce any special casing around undefined. There's always a semantic gap, and fulfilling with a different value is not a common use case anyway. You rarely see any return statements in normal finally blocks either, most people would even consider them a code smell.
I have below code:
let func = () => {
return new Promise((resolve) => {
setTimeout(() => {
console.log("two");
resolve();
}, 3000);
})
};
let func2 = async () => {
console.log("one");
await func();
console.log("three");
}
(async () => {
await func2();
console.log("main"); // This should never be executed
})()
Noticed func2 never returns a value, the promise returned by func2 should never be fullfilled in my opinion. Hence console.log("main") should never be executed. However it is executed after console.log("three"). Can somebody explain this to me?
Noticed func2 never returns a value, the promise returned by func2 should never be fullfilled in my opinion.
That is not how async functions work. Your func2 returns when it is done executing. The return value of a function with no return statement is the specific value undefined. So, undefined becomes the resolved value of the promise. Remember, in Javascript, undefined is a specific value. It's as if you did return undefined at the end of your function block. So, since undefined is the return value, that becomes the resolved value of the async promise.
To fully cover all the bases, async functions always return a promise and that promise gets a resolved/rejected value one of these ways:
1. When you explicitly return a value from the function. That becomes the resolved value of the promise that the async function returns.
async function test() {
return "hello";
}
test().then(val => {
console.log(val); // "hello"
});
2. When you throw an exception. The exception becomes the reject reason of the promise that the async function returns.
async function test() {
throw new Error("ouch");
}
test().catch(err => {
console.log(err); // Shows error object with message "ouch"
});
3. When you return another promise. That promise is chained to the one that the async function returns and the promise that the async function returns will follow the one you returned (resolve when it resolves with the same value or reject with the same reason).
async function test() {
return new Promise(resolve => {
setTimeout(() => {
resolve("hi");
}, 1000);
});
}
test().then(val => {
console.log(val); // "hi"
});
4. When you return nothing. That is the same as in regular functions and it's equivalent to a return undefined at the end of the function block so the resolved value takes on the value of undefined.
So, this:
async function test() {
console.log("hi");
}
test().then(val => {
console.log(val); // undefined
});
Works exactly the same as this:
async function test() {
console.log("hi");
return undefined;
}
test().then(val => {
console.log(val); // undefined
});
A function that does not explexitly return something, actually returns undefined:
function test() { }
console.log(test());
Its the same with async functions, they also resolve to undefined when no other value was returned.
An async function doesn't need a return value in order to resolve. It is considered resolved when it finishes executing without an error.
If you throw new Error() inside of func2, console.log("main") will never be executed.
When you don't return from a function it implicitly returns a default value — normally undefined. So the promise returned by func2 will still resolve when the function returns.
From MDN:
A function without a return statement will return a default value. In
the case of a constructor called with the new keyword, the default
value is the value of its this parameter. For all other functions, the
default return value is undefined.
You can see this in your code if you alter it to this:
(async () => {
func2()
.then(d => console.log(d));
})()
With regard to these great two sources: NZakas - Returning Promises in Promise Chains and MDN Promises, I would like to ask the following:
Each time that we return a value from a promise fulfillment handler, how is that value passed to the new promise returned from that same handler?
For instance,
let p1 = new Promise(function(resolve, reject) {
resolve(42);
});
let p2 = new Promise(function(resolve, reject) {
resolve(43);
});
let p3 = p1.then(function(value) {
// first fulfillment handler
console.log(value); // 42
return p2;
});
p3.then(function(value) {
// second fulfillment handler
console.log(value); // 43
});
In this example, p2 is a promise. p3 is also a promise originating from p1's fulfillment handler. However p2 !== p3. Instead p2 somehow magically resolves to 43 (how?) and that value is then passed to p3's fulfillment handler. Even the sentence here is confusing.
Could you please explain to me what exactly is going on here? I am totally confused over this concept.
Let’s say that throwing inside then() callback rejects the result promise with a failure, and returning from then() callback fulfills the result promise with a success value.
let p2 = p1.then(() => {
throw new Error('lol')
})
// p2 was rejected with Error('lol')
let p3 = p1.then(() => {
return 42
})
// p3 was fulfilled with 42
But sometimes, even inside the continuation, we don’t know whether we have succeeded or not. We need more time.
return checkCache().then(cachedValue => {
if (cachedValue) {
return cachedValue
}
// I want to do some async work here
})
However, if I do async work there, it would be too late to return or throw, wouldn’t it?
return checkCache().then(cachedValue => {
if (cachedValue) {
return cachedValue
}
fetchData().then(fetchedValue => {
// Doesn’t make sense: it’s too late to return from outer function by now.
// What do we do?
// return fetchedValue
})
})
This is why Promises wouldn’t be useful if you couldn’t resolve to another Promise.
It doesn’t mean that in your example p2 would become p3. They are separate Promise objects. However, by returning p2 from then() that produces p3 you are saying “I want p3 to resolve to whatever p2 resolves, whether it succeeds or fails”.
As for how this happens, it’s implementation-specific. Internally you can think of then() as creating a new Promise. The implementation will be able to fulfill or reject it whenever it likes. Normally, it will automatically fulfill or reject it when you return:
// Warning: this is just an illustration
// and not a real implementation code.
// For example, it completely ignores
// the second then() argument for clarity,
// and completely ignores the Promises/A+
// requirement that continuations are
// run asynchronously.
then(callback) {
// Save these so we can manipulate
// the returned Promise when we are ready
let resolve, reject
// Imagine this._onFulfilled is an internal
// queue of code to run after current Promise resolves.
this._onFulfilled.push(() => {
let result, error, succeeded
try {
// Call your callback!
result = callback(this._result)
succeeded = true
} catch (err) {
error = err
succeeded = false
}
if (succeeded) {
// If your callback returned a value,
// fulfill the returned Promise to it
resolve(result)
} else {
// If your callback threw an error,
// reject the returned Promise with it
reject(error)
}
})
// then() returns a Promise
return new Promise((_resolve, _reject) => {
resolve = _resolve
reject = _reject
})
}
Again, this is very much pseudo-code but shows the idea behind how then() might be implemented in Promise implementations.
If we want to add support for resolving to a Promise, we just need to modify the code to have a special branch if the callback you pass to then() returned a Promise:
if (succeeded) {
// If your callback returned a value,
// resolve the returned Promise to it...
if (typeof result.then === 'function') {
// ...unless it is a Promise itself,
// in which case we just pass our internal
// resolve and reject to then() of that Promise
result.then(resolve, reject)
} else {
resolve(result)
}
} else {
// If your callback threw an error,
// reject the returned Promise with it
reject(error)
}
})
Let me clarify again that this is not an actual Promise implementation and has big holes and incompatibilities. However it should give you an intuitive idea of how Promise libraries implement resolving to a Promise. After you are comfortable with the idea, I would recommend you to take a look at how actual Promise implementations handle this.
Basically p3 is return-ing an another promise : p2. Which means the result of p2 will be passed as a parameter to the next then callback, in this case it resolves to 43.
Whenever you are using the keyword return you are passing the result as a parameter to next then's callback.
let p3 = p1.then(function(value) {
// first fulfillment handler
console.log(value); // 42
return p2;
});
Your code :
p3.then(function(value) {
// second fulfillment handler
console.log(value); // 43
});
Is equal to:
p1.then(function(resultOfP1) {
// resultOfP1 === 42
return p2; // // Returning a promise ( that might resolve to 43 or fail )
})
.then(function(resultOfP2) {
console.log(resultOfP2) // '43'
});
Btw, I've noticed that you are using ES6 syntax, you can have a lighter syntax by using fat arrow syntax :
p1.then(resultOfP1 => p2) // the `return` is implied since it's a one-liner
.then(resultOfP2 => console.log(resultOfP2));
In this example, p2 is a promise. p3 is also a promise originating from p1's fulfillment handler. However p2 !== p3. Instead p2 somehow magically resolves to 43 (how?) and that value is then passed to p3's fulfillment handler. Even the sentence here is confusing.
a simplified version how this works (only pseudocode)
function resolve(value){
if(isPromise(value)){
value.then(resolve, reject);
}else{
//dispatch the value to the listener
}
}
the whole thing is quite more complicated since you have to take care, wether the promise has already been resolved and a few more things.
I'll try to answer the question "why then callbacks can return Promises themselves" more canonical. To take a different angle, I compare Promises with a less complex and confusing container type - Arrays.
A Promise is a container for a future value.
An Array is a container for an arbitrary number of values.
We can't apply normal functions to container types:
const sqr = x => x * x;
const xs = [1,2,3];
const p = Promise.resolve(3);
sqr(xs); // fails
sqr(p); // fails
We need a mechanism to lift them into the context of a specific container:
xs.map(sqr); // [1,4,9]
p.then(sqr); // Promise {[[PromiseValue]]: 9}
But what happens when the provided function itself returns a container of the same type?
const sqra = x => [x * x];
const sqrp = x => Promise.resolve(x * x);
const xs = [1,2,3];
const p = Promise.resolve(3);
xs.map(sqra); // [[1],[4],[9]]
p.then(sqrp); // Promise {[[PromiseValue]]: 9}
sqra acts like expected. It just returns a nested container with the correct values. This is obviously not very useful though.
But how can the result of sqrp be interpreted? If we follow our own logic, it had to be something like Promise {[[PromiseValue]]: Promise {[[PromiseValue]]: 9}} - but it is not. So what magic is going on here?
To reconstruct the mechanism we merely need to adapt our map method a bit:
const flatten = f => x => f(x)[0];
const sqra = x => [x * x];
const sqrp = x => Promise.resolve(x * x);
const xs = [1,2,3];
xs.map(flatten(sqra))
flatten just takes a function and a value, applies the function to the value and unwraps the result, thus it reduces a nested array structure by one level.
Simply put, then in the context of Promises is equivalent to map combined with flatten in the context of Arrays. This behavior is extremely important. We can apply not only normal functions to a Promise but also functions that itself return a Promise.
In fact this is the domain of functional programming. A Promise is a specific implementation of a monad, then is bind/chain and a function that returns a Promise is a monadic function. When you understand the Promise API you basically understand all monads.
(function() {
"use strict";
var storage = chrome.storage.sync;
var localStorage = null;
function getOutsideScope(property) {
if (localStorage.hasOwnProperty(property)) {
return localStorage[property];
}
}
function fulfill(data) {
return data;
}
function rejected(err) {
log(err);
}
window.app.storage = {
get: function(storageKey, storageProp) {
var promise = new Promise(function(fullfill, reject) {
chrome.storage.sync.get(storageKey, function(data) {
if (data.hasOwnProperty(storageKey)) {
fullfill(data[storageKey]);
} else {
reject(new Error(storageKey + " does not exist in the storage values."));
}
});
});
return promise.then(fulfill, rejected);
},
set: function(storageKey, storageItem) {
},
onChanged: function(fn) {
}
};
})();
So the above is my IIFE wrapper for chrome storage, and well the return is being a pain in the bleep. So I decided to give Promises a try, this is my first time so don't be too rough on me on this. Basically this is what I want to do
var property = app.storage.get("properties");
//property should equal "value"
//except it returns undefined
So adding the promises it does get the value except it returns this
Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: "value"}
Am I doing something wrong with Promises I've tried reading HTML5Rocks, the MDN, and video tutorials except it doesn't really mention much of how to return a value. This does NOT work
get:function(storageKey,storageProp) {
chrome.storage.sync.get(storageKey,function(data) {
//for simplicity and no error checking -_-
return data[storageKey];
});
}
The function returns exactly what it is supposed to return: A promise. To get the value once the promise is fulfilled, you add a callback via .then:
app.storage.get("properties").then(function(property) {
// property will be "value"
});
From MDN:
A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.
[...]
A pending promise can become either fulfilled with a value, or rejected with a reason (error). When either of these happens, the associated handlers queued up by a promise's then method are called.