What is the point of promises in JavaScript?

情到浓时终转凉″ 提交于 2019-12-02 14:53:38

What is the point of promises in JavaScript?

See: You're Missing the Point of Promises.


Cannot consider all of the nuances relevant to using Promise alone. Browse the promise tag to read other users' questions and answers posted by users whom post frequently at promise tag. Ask questions as to specific cases at comments at those questions and answers, for your own edification.


You get the value of a Promise using .then() or .catch(), not by checking the value of a variable outside of Promise chain.

Disregard "present" and "future". Focus on implementing code within .then() and, or .catch(). All other code referencing an asynchronous value referenced by an identifier will not be reliable.

let id = void 0;

let promise = new Promise(resolve => 
                setTimeout(() => {id = 123; resolve(id) }, Math.random() * 2000)
              );

// this is not accurate
console.log(`id: ${id}`); // what is `id` here?

promise.then(res => console.log(`id: ${res}`));

Note also, function passed to Promise constructor as executor is called immediately

let id = void 0;

let promise = new Promise(resolve => 
                setTimeout(resolve, Math.random() * 2000, id = 123)
              );

// is this accurate?
console.log(`id: ${id}`); // what is `id` here?

promise.then(res => console.log(`id: ${res}`));

return a value from .then().

return a value from .then(). Use .map() instead of .forEach()

Promise.resolve(123)
.then(data => console.log(data))
.then(res => console.log(res)) // `undefined`

Promise.resolve(123)
.then(data => { console.log(data); return data})
.then(res => console.log(res)) // `123`

Use .map() instead of .forEach()

let fn = (id) =>  new Promise(resolve => 
                    setTimeout(resolve, Math.random() * 2000, id)
                  );
                  
Promise.all([1,2,3].map(fn))
.then(data => Promise.all(data.forEach(id => fn(id * 10))))
.then(data => console.log(`data: ${data}`)); // where is `data`

                  
Promise.all([1,2,3].map(fn))
.then(data => Promise.all(data.map(id => fn(id * 10))))
.then(data => console.log(`data: ${data}`)); // `[10, 20, 30]`

A handled rejection or error is converted to a resolved Promise is not thrown or rejection returned

let fn = () => new Promise((resolve, reject) => 
                setTimeout((id) => {reject(new Error(id)) }, Math.random() * 2000, 123)
              )

fn().then(res => console.log(`id: ${res}`))
.catch(err => console.log(`err: ${err}`))
.then(res => console.log(`res: ${res}`)) // `undefined`

fn().then(res => console.log(`res: ${res}`))
.catch(err => { console.log(`err: ${err}`); return err })
// `.then()` is not called, function passed to `.catch()` is called
.then(res => console.log(`res: ${res}`)) 
.catch(err => console.log(`err: ${err}`)) // `123`
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!