somethingThatReturnsPromiseWithoutError()
.then((res) => {
return Promise.reject("some error");
})
.catch((err) => {
console.log(err); // => some error
});
Promise.resolve() and Promise.reject() return a promise resolved or rejected to the value passed in the first argument. Returning a promise in the fulfillment function passed to .then() chains the promises together. somethingThatReturnsPromise()
.then((foo) => {
return foo.bar;
// Or if you like it more verbose
return Promise.resolve(foo.bar);
// Or pass bar to a function modifying bar that returns a promise
return modifyBarReturnPromise(foo.bar);
})
.then((newBar) => {
console.log(newBar);
});
In your case, if you need step1Val in next promise chain, I personally do this, however people more familiar with promises may know of a better way to do it (maybe with something like Promise.all() or Promise.props() in the BlueBird library). somethingThatReturnsPromise()
.then((first) => {
doSomethingWithFirstAndReturnPromise(first)
.then((second) => {
console.log(first + second);
});
});then() returns a new promise resolved to the return value of the function. However, if that value is itself a promise, then it follows the promise chain and passes the eventual state to the next then()/catch() call.
.then(val => doSomeStuff())
Thats it. The resulting promise will get resolved/rejected based on the return result of doSomeStuff()You can also use throw to reject a promise manually, or return Promise.reject()
.then(val => {
if (something) return successVal;
else throw new Error("Failure");
});
For more complex scenarios where I need the values from previous actions, I like the forgoing the chaining and using a join helper to unwrap any set of promises as needed: let url = getUrl(resource);
let data = url.then(url => fetch(url))
let updateData = d => _.assign(d, {field: 'newVal'}
let update = join(url, data, (url, data) => sendUpdate(url, updateData(data))The spec on mdn[0] doesn't mention asynchronous `then` or `catch` behavior. If the callback in Jquery `Deferred#then` returns a Deferred that deferred will be returned by `then`.
// Basic async function, resolves after n milliseconds
function wait(n) {
var promise = $.Deferred();
setTimeout(promise.resolve, n);
return promise;
}
wait(10)
.then(function() {
console.log('first'); // prints first after 10 milliseconds
return wait(10);
})
.then(function() {
console.log('second'); // prints second after 20 milliseconds
return 'done';
})
You can 'flip' a failed promise by returning a resolve promise in the fail callback. var promise = $.Deferred();
setTimeout(promise.reject, 100)
promise.then(null, function () {
return $.Deferred().resolve([]);
}).done(function(arg) {
console.log(arg); // Prints '[]'
})
[0] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... function doSomething() {
return new Promise((resolve,reject)={
setTimeout(reject,100);
})
.catch(() => [])
}
doSomething().then((arg) => console.log(arg));The docs for Promise say that then() returns a promise. Are you saying it returns the original promise (ie. this)?
> But if your call to then isn't a Promise or a function that returns a Promise, your chain ends.
I don't think this is correct. The docs show examples of chains of then() calls where the intermediate function isn't returning a promise. See "chaining": https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
It returns a promise, right?
> var foo = Promise.resolve([1,2,3]).then(function() { return 5 })
> foo
< Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: 5}IMO you should use Babel and take advantage.
async function foo() {
try {
const valueOne = await promiseReturningFunction();
const valueTwo = await anotherAsyncFunction(valueOne);
return valueTwo;
} catch (err) {
alert(err);
}
}
foo(); //Returns a Promise.
----In this example, I've sequenced the resolution of two promises (async functions return Promises when invoked)
If either of these Promises reject or throw an error, or if any of the code within the try {} block throws an error, the error will be caught inline in the catch block (one area only).
You can also see that both Promise's return values are in-scope and continually usable (vs. losing scope with 'then' chains).
IMO threading an object through is probably the best method, unfortunately. You could use an Immutable Record or something to help keep it under control.
I would personally just use async/await to more explicitly handle the sequencing/binding.
Also how do you return a value from the second callback? Just return?
If throw and return work that way for then() functions, why not the same for the initial function?
Also some of indexedDB doesn't seem like it would fit with promises, since some operations have 3 or more callbacks (onsuccess, onerror, onupgradeneeded).
I can see the benefits of the indexedDb behavior: an open transaction is an exclusive resource, so leaving one dangling locks out other transactions. The auto-commit behavior means it's a lot harder to accidentally leave a transaction dangling. But it is unfortunate that this makes it not play nicely with promises.
ie. I can't write:
Instead I'm having to write this as the following, which is more verbose: Another bummer of this style is that that the second step doesn't get access to the first step's value.