为了充分利用本文,请确保您了解有关同步和异步编程以及javascript回调的基础知识,但是,我将尽量使大部分内容远离这些主题,以便您可以理解至少有85%
了解承诺
假设有一位朋友来找您,以帮助您,您答应他从自动柜员机中取出现金后给您现金。
- 您转到自动提款机,刷卡,然后发现由于某些原因您的帐户已被冻结,无法取出钱。
- 然后,您回到朋友身边,告诉他您不能给他钱,因为您的帐户被冻结了。 因此,违反了您的诺言。
//You have made promise to your friend and you leave for bank
if (everythingGoesWell) {
return theMoney //Promise is fulfilled
}
else {
return "Account_Frozen" //Promise failed
}
在JavaScript中使用async
处理async
操作。 它们是特殊的对象,它们链接实际的输出(在上面的示例中,这是必需的金钱)以及我们可能无法获得输出的原因(冻结的帐户)。
承诺的状态
JavaScript promise
已settled
或pending
。 我们可以使用Promise
构造函数创建一个promise
。
var thePromise = new Promise (executor())
executor函数是promise构造函数的回调。 它需要两个回调: resolve
和reject
作为参数。
- 当实际履行
promise
时,将使用resolve
回调。 它以输出值作为参数。 - 当无法实现
promise
时,将使用reject
回调。 它以理由为依据。
当我们创建一个promise
它会初始化为pending
状态。 一旦执行程序运行,状态将变为已settled
,可以resolved
或rejected
。
实施:代码段
var thePromise = new Promise ( function ( resolve,reject ) { // Try to take out money from atm withdraw( function ( error,money ) { // If withdrawal failed, tell why if (error) reject (error) // else return the money else resolve (money) }) })
如果您没有回调和回调地狱的经验,那么承诺可能会很忙。 但是,一旦您掌握了这一概念,就再也没有回头路了!
then
和catch
子句catch
函数附加到promise
,当promise
被拒绝时执行。 它通过reject
方法发送的错误作为参数。then
函数附加到promise
,该promise
在promise
解析后执行。 它发送通过resolve
方法发送的值作为参数。也有一个
finally
子句。 无论promise
解决还是拒绝,它都会执行。 它没有参数。var thePromise = new Promise ( function ( resolve,reject ) { // Try to take out money from atm withdraw( function ( error,money ) { // If withdrawal failed, tell why if (error) reject (error) // else return the money else resolve (money) }) }) thePromise.then( function ( money ) { // This function is executed when the above promise resolves and returns an //amount of money }) thePromise.catch( function ( error ) { // This function is executed when the above promise rejects due to an error }) thePromise.finally( function () { // This function is executed after the promise is resolved or rejected. })
谢谢! 反馈,建议和更正受到高度赞赏。 请写评论%-)
Jaskirat S.Grewal(@thejscode)
先前发布在 https://dev.to/thejscode/javascript-promises-for-beginners-31aj
翻译自: https://hackernoon.com/javascript-promises-from-scratch-qsp3umn