Promise.resolve(value) creates a promise that is already resolved with that value. It is useful when a function should return a promise whether its result is already available or still needs to be fetched. section 30.3
const transactions = {};
getTransaction(id) {
if (transactions[id]) {
return Promise.resolve(transactions[id]); 1
} else {
const loading = load(`/transactions/${id}`); 2
loading.then(transaction => {
transactions[id] = transaction; 3
});
return loading; 4
}
}
getTransaction(405).then(transaction => {
// do something with transaction
}, err => { 5
// handle error
})
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":4,\"ch\":55},{\"line\":4,\"ch\":56}],[{\"line\":6,\"ch\":55},{\"line\":6,\"ch\":56}],[{\"line\":8,\"ch\":55},{\"line\":8,\"ch\":56}],[{\"line\":10,\"ch\":55},{\"line\":10,\"ch\":56}],[{\"line\":14,\"ch\":15},{\"line\":14,\"ch\":16}],[{\"line\":14,\"ch\":17},{\"line\":14,\"ch\":18}],[{\"line\":16,\"ch\":55},{\"line\":16,\"ch\":56}]]"}
!@%STYLE%@!
In the transaction lookup, cached data is wrapped with Promise.resolve; otherwise, the function returns the promise from the network request. Callers can attach success and error handling through .then() either way. section 30.3
