2017-05-15 49 views
-3

一诺是这可能是可用JavaScript中的承诺有什么意义?

(...)值,现在,还是将来,或从不(来源:MDN)

所以可以说我有一个应用程序,它想与照片一起工作。照片被加载,例如算法在后台运行后(或其他某种延迟)。现在我想检查一下,如果图片在未来可用,通过使用承诺,而不是回调。

要检查,如果图像是可用的,我可以用下面的代码:

function loadImage(url) { 
    return new Promise((resolve, reject) => { 
    let image = new Image() 

    image.onload = function() { 
     resolve(image) 
    } 

    image.onerror = function() { 
     let message = 
     'Could not load image at ' + url 
     reject(new Error(msg)) 
    } 

    image.src = url 
    }) 
} 

的承诺,属于这将是这个样子:

Promise.all([ 
    loadImage('images/pic1.jpg'), 
    loadImage('images/pic2.jpg') 
]).then((images) => { 
    images.forEach(img => addImg(img.src)) 
}).catch((error) => { 
    // handle error 
}) 

这不会因为如果图片在目前,而不是在未来可用,承诺将查找。图片将在一秒钟内出现,但承诺将返回一个错误。

我在这里没有得到有关承诺的信息?对我而言,看起来就像是检查的整个未来方面,如果图片可用取决于loadImage(url)而不是实际承诺本身。

PS:实例启发funfunfunction


的承诺怎么会知道什么时候解决?

据我了解,它不会“听”周围的其他代码,更不用说可能在后台运行的框架。我会假设在这个例子中它会是这样的:诺言检查是否有图片 - >它们仍然在后台工作 - >承诺解决并抛出错误 - >算法完成与图片 - >图片可用?

+0

_“仍然承诺会返回一个错误。” _哪里是'在问javascript'错误? – guest271314

+0

**请注意,这是假设!**我知道还有其他方法可以解决此问题。我想了解承诺如何帮助我在这里,以及为什么一切似乎取决于loadImage(url),而不是承诺本身 – User12547645

+3

*,因为承诺将查找如果图片可用在现在,而不是在未来* - 关于未来的事情是它有一个最终成为现在的习惯。 –

回答

1

JavaScript中的承诺有什么意义?

参见:You're Missing the Point of Promises


不能考虑所有相关的单独使用Promise的细微差别。浏览promise标签,阅读经常以promise标签发布的用户发布的其他用户的问题和答案。在这些问题和答案的评论中提出关于具体案例的问题,供您自己的启发。


你,不会通过检查Promise链可变之外的价值得到使用.then().catch()一个Promise的价值。

无视“现在”和“未来”。专注于在.then().catch()之内执行代码。引用由标识符引用的异步值的所有其他代码都不可靠。

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}`));

还要注意,函数传递给Promise构造函数执行从.then()立即

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值调用。

return.then()得到的值。使用.map()代替.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`

使用.map()代替.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]`

甲处理排斥或误差被转换为解决Promise不是throw n或拒绝返回

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`