Fai*_*med 6 javascript node.js promise
我试图从承诺中返回承诺,然后Promise.all像这样运行:
updateVideos()
.then(videos => {
return videos.map(video => updateUrl({ id: video, url: "http://..." }))
})
.then(Promise.all) // throw Promise.all called on non-object
Run Code Online (Sandbox Code Playgroud)
我怎么能用这种呢Promise.all?我知道.then(promises => Promise.all(promises))有效.但是,只是想知道为什么失败了.
Express res.json也会发生这种情况.错误信息不同,但我认为原因是一样的.
例如:
promise().then(res.json) // Cannot read property 'app' of undefined
Run Code Online (Sandbox Code Playgroud)
不起作用但是
promise().then(results =>res.json(results))
Run Code Online (Sandbox Code Playgroud)
确实.
all需要通过this引用Promise(或子类)来调用,因此您需要:
.then(promises => Promise.all(promises))
Run Code Online (Sandbox Code Playgroud)
要么
.then(Promise.all.bind(Promise))
Run Code Online (Sandbox Code Playgroud)
这很重要,因为all在Promise子类中继承时需要正常工作.例如,如果我这样做:
class MyPromise extends Promise {
}
Run Code Online (Sandbox Code Playgroud)
......那么创造的承诺MyPromise.all应该由MyPromise而不是创造Promise.所以all使用this.例:
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);
});Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper {
max-height: 100% !important;
}Run Code Online (Sandbox Code Playgroud)
规范中的详细信息.(为了理解为什么在我打电话的时候打五次电话,我将不得不重新阅读.)MyPromiseMyPromise.all
| 归档时间: |
|
| 查看次数: |
361 次 |
| 最近记录: |