Calling Promise.all challenges Promise.all to a non-object?

I am trying to return promises from a promise and run Promise.all as follows:

 updateVideos() .then(videos => { return videos.map(video => updateUrl({ id: video, url: "http://..." })) }) .then(Promise.all) // throw Promise.all called on non-object 

How can I use this type of Promise.all . I know .then(promises => Promise.all(promises)) works. But just trying to understand why this failed.

This also happens with Express res.json . The error message is different, but I think the reason is the same.

For instance:

 promise().then(res.json) // Cannot read property 'app' of undefined 

doesn't work but

 promise().then(results =>res.json(results)) 

does.

+5
source share
1 answer

all needs to be called using this , referencing Promise (or a subclass), so you will need:

 .then(promises => Promise.all(promises)) 

or

 .then(Promise.all.bind(Promise)) 

This is important because all should work correctly when inherited in Promise subclasses. For example, if I do this:

 class MyPromise extends Promise { } 

... then the promise created by MyPromise.all should be created by MyPromise , not Promise . Therefore, all uses this . Example:

 class MyPromise extends Promise { constructor(...args) { console.log("MyPromise constructor called"); super(...args); } } console.log("Creating two generic promises"); const p1 = Promise.resolve("a"); const p2 = Promise.resolve("a"); console.log("Using MyPromise.all:"); const allp = MyPromise.all([p1, p2]); console.log("Using then on the result:"); allp.then(results => { console.log(results); }); 
 .as-console-wrapper { max-height: 100% !important; } 

Details in the specification . (Which I will have to re-read to understand why the five MyPromise calls MyPromise made when I call MyPromise.all in the above.)

+5
source

Source: https://habr.com/ru/post/1274887/


All Articles