JavaScript中的promise的意义是什么? [英] What is the point of promises in JavaScript?

查看:38
本文介绍了JavaScript中的promise的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个承诺就是一个

(...)值,现在,将来或永远不会可用(来源:MDN)

(...) value which may be available now, or in the future, or never (Source: MDN)

所以可以说我有一个想要处理图片的应用程序.图片已加载,例如算法在后台使用它(或其他某种延迟)后.现在,我想使用承诺而不是回调来检查图片是否在未来中可用.

So lets say I have an app which wants to work with pictures. The pictures are loaded e.g. after an algorithm works with it in the background (or some other sort of delay). Now I want to check, if the pictures are available in the future, by using a promise, not a callback.

要检查图像是否可用,我可以使用以下代码:

To check, if an image is available, I could use the following code:

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

属于这个的诺言看起来像这样:

The promise, which belongs to this would look something like this:

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

这完全无济于事,因为如果图片在礼物(而不是未来)中可用,诺言就会出现.图片将在一秒钟之内出现,但诺言仍将返回错误.

This will not help my at all, because the promise will look up if the pictures are available in the present, not in the future. The pictures will be there in a second, still the promise will return an error.

在这里我对诺言没有什么了解?对我来说,检查的整个未来方面似乎是否可用,取决于loadImage(url)而不是实际的承诺本身.

What do I not get about promises here? For me it looks like the entire future aspect of checking, if the pics are available depends on loadImage(url) not on the actual promise itself.

PS:受funfunfunction启发的示例

PS: Example inspired by funfunfunction

诺言如何解决?

据我了解,它不会侦听"它周围的其他代码,更不用说可能在后台运行的框架了.我假设在此示例中结果如下:promise检查图片是否可用->它们仍在后台使用-> Promise解析并引发错误->图片处理算法已完成->图片是否可用?/p>

To my understanding it does not "listen" to the other code around it, let alone a framework which might run in the background. I would assume in this example it would turn out like this: promise checks if pictures are available -> they are still worked with in the background -> promise resolves and throws error -> algorithm is finished with pictures -> pictures are available ?

推荐答案

JavaScript中的promise的意义是什么?

What is the point of promises in JavaScript?

请参阅:您错过了承诺的重点.

不能考虑与单独使用Promise有关的所有细微差别.浏览promise标记以阅读经常在promise标记上发布的用户发布的其他用户的问题和答案.提出自己的想法,在这些问题和答案的评论中针对特定案例提出问题.

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.

您可以使用.then().catch()来获取Promise的值,而不是通过检查Promise链之外的变量的值来获得.

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

忽略现在"和未来".着重在.then().catch()中实现代码.引用由标识符引用的异步值的所有其他代码将不可靠.

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

还请注意,作为执行程序传递给Promise构造函数的函数将立即被调用

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 .then()中的值.

return .then()中的值.使用.map()代替.forEach()

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`

使用.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或返回了拒绝

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`

这篇关于JavaScript中的promise的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆