田辺  亮介

田辺 亮介

1658826444

JavaScript Promise 完整指南

JavaScript Promise 完整指南

JavaScript 是單線程腳本語言。一切都按順序發生;它是逐行編寫的。但是,異步操作 按照它們完成的順序發生。 

事件非常適合在同一個對像上多次發生的事情,如 keyup、touchstart、mouseover 等。

對於這些事件,您不必關心在附加偵聽器之前發生了什麼。但是當涉及到成功/失敗的異步行為時,回調函數 不如promises有用。

Javascript 承諾

Javascript Promise是一個特殊的 JavaScript 對象,它將“生產代碼”和“消費代碼”鏈接在一起。承諾只能成功或失敗一次。它不能成功或失敗兩次或更多次,也不能從成功切換到失敗,反之亦然。

如果promise成功或失敗,並且您稍後添加了成功/失敗回調,則將根據輸出調用正確的回調,即使事件發生得更早。

Promise構造函數接受一個參數:一個 回調函數,它有兩個參數被調用來解析和拒絕。因此,我們可以使用Promise作為兩種不同的方法。

  1. 創建一個承諾
  2. 消費承諾

創建一個承諾

讓我們舉一個例子來說明如何創建一個 javascript 承諾。

 

// server.js

const prom = new Promise(function(resolve, reject) {
  setTimeout(() => {
    resolve('Promise is created and consumed');
  }, 200);
});

因此,在這裡,我們創建了一個javascript  promise 對象並將兩個參數傳遞給Promise構造函數,調用該構造函數來解析 和 拒絕

在消費的時候,如果promise被解決了,那麼我們就可以使用then() 函數來消費該值;如果 promise 被拒絕,那麼我們會在catch() 塊中得到錯誤值。

消費承諾

因此,如果我們解析函數,我們會在then()塊中獲取值。讓我們看下面的例子,看看終端內的輸出。

// server.js

const prom = new Promise(function(resolve, reject) {
  setTimeout(() => {
    resolve('Promise is created and consumed');
  }, 200);
});

prom.then(value => {
  console.log(value);
});

現在,通過鍵入以下命令在node.js中運行上述文件。

Javascript Promise 示例教程

承諾也被拒絕,在這種情況下,我們的代碼看起來像下面的代碼片段。

// server.js

const prom = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('Promise is rejected');
  }, 200);
});

prom.catch(error => {
  console.log(error);
});

輸出

Javascript 承諾拒絕

因此,如果提供了一個很好的例子,理解 Promise 並不是那麼困難。

執行器通常會啟動一些異步工作,然後,一旦完成,要么調用resolve函數來解決一個承諾,要么在發生錯誤時拒絕它。

如果在 executor 函數中拋出錯誤,則 promise 被拒絕。執行器的返回值被忽略。

Javascript 中的承諾狀態

Promise是在創建 Promise 時不一定知道的值的代理。因此,promise 允許您將處理程序與異步操作的最終成功或失敗相關聯。

這讓異步方法像同步方法一樣返回值。異步方法不是立即返回最終值,而是返回一個在未來某個時間點提供值的承諾。

Promise 處於以下狀態之一: 

  1. Pending:初始狀態或未決狀態,既不履行也不拒絕。
  2. Fulfilled:表示操作成功完成。
  3. Rejected:表示操作失敗。

承諾方法

Javascript Promise有以下方法。

承諾.all()

它返回當可迭代參數中的所有承諾都已履行或一旦可迭代參數中的一個承諾拒絕承諾時被拒絕的承諾。如果返回的 Promise 被實現,它會使用一個來自已實現的 Promise 的值數組來實現,其順序與可迭代對像中定義的相同。
如果返回的 Promise 被拒絕,它會因為 iterable 被拒絕的第一個 Promise 的原因而被拒絕。

Promise.race(可迭代)

它返回履行或拒絕的承諾,作為可迭代履行或拒絕中的承諾之一,並帶有來自該承諾的價值或理由。

Promise.reject(原因)

返回因給定原因而被拒絕的 Promise 對象。

Promise.resolve (值)

它返回使用給定值解析的 Promise 對象。

異步等待承諾示例

讓我們舉一個例子來說明如何將 Promise 與async-await一起使用。

// server.js

function square(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(Math.pow(x, 2));
    }, 2000);
  });
}

async function layer(x)
{
  const value = await square(x);
  console.log(value);
}

layer(10); // 100

所以,在輸出中,你會得到 100。首先,它會調用async 函數 層,然後它會等待 promise 被執行或被拒絕,然後它會給我們輸出。

在這裡,我們必須使用setTimeout() 函數來導致手動延遲執行來模擬 AJAX 請求。如果我們拒絕,則得到錯誤對象

Promises 中的錯誤處理很容易,因為它只給出一次,無論是完成還是拒絕。所以它是創建回調地獄的回調函數的最佳替代品。

鏈接:https ://appdividend.com/2022/07/22/javascript-promise/

#javascript

What is GEEK

Buddha Community

JavaScript Promise 完整指南
Julie  Donnelly

Julie Donnelly

1602406920

JavaScript Promise: Methods Comparison

Introduction

Promises in JavaScript are used to handle asynchronous operations by keeping track of whether a certain event has happened. If that certain event has taken place, it determines what happens next. Promises return a value which is either a resolved value or a reason why it’s rejected. They can handle multiple asynchronous operations easily and they provide better error handling than callbacks and events.

Callback: A callback is a function that is passed into another function as an argument to be executed later.

Events: Events provide a dynamic interface to a WebPage and are connected to elements in the Document Object Model(DOM), for example: onclick(), onmouseover() etc.

A Promise has four states

Pending: Before the event has happened, the promise is in the pending state.

Settled: Once the event has happened it is then in the settled state.

Fulfilled: Action related to the promise has succeeded.

Rejected: Action related to the promise has failed.

#javascript #javascript-development #javascript-tutorial #promises #javascript-tips

Promise.allSettled() vs Promise.all()

Promise.allSetlled() is recently introduced in ECMA 2020.
Check out how it is different from Promise.all()

https://www.geekstutorialpoint.com/2020/05/promiseallsettled-vs-promiseall.html

#javascript #promise.all #promise.allsettled #ecma #promise #jquery

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Hugo JS

Hugo JS

1599295469

What is Callback-Function in JavaScript? How it is Replaced By Promises?

Let us understand term _Callback _by an real-world example: Suppose, you are calling to your Girlfriend (If you have) and she is busy in another call then she send message to you : “I am busy right now, Call back you later.!!”. After completing her work, she calls you back and this is what call back in JavaScript as well.

In JavaScript, When a function is executing (Girlfriend is talking with someone) then after function execution is completed another function is started for execution this is call back function.

Now you are thinking that its depend upon when, where you are calling function and all function call is “Call-back function”. Image for post

Here, _printWorld() _function is executed after _printHello() _complete its execution but this is not call-back function example because _printHello() _is not Asynchronous function. Suppose, _printHello() _prints after 1 Second then _printWorld() _executes first.

Image for post

What if we want “Hello World” output when Asynchronous function is there. We can pass function as argument and calls it after _printHello() _complete its execution. Here below code snippet of how _function pass as argument _:

Image for post

Callback function can be defined as a function passed by argument and executes when one function completes its execution.

Suppose, If you have API (Application Programming Interface) to get Students Roll numbers and select one of Roll number — getting that roll number’s data and print that data. We don’t have API to get students data so we are using _setTimeout() _Async function and getting roll number after 2s, We are also selecting one of roll number manually after 2s and print Roll number’s data after 2s. This can be done by call back function.

Image for post

The program became complex and complex if we have too many things to do like Getting Students data, Selecting one of them student, get student’s roll number and get result by roll number then it become very complex. If you have any Error in this then debugging is also tedious task, this things is called “Callback Hell”, which is shape like “Pyramid Of Doom”.

To overcome with this problem, Promises is introduced in JavaScript. Promises has three states : Pending, Resolved, Reject. Promises is created by Constructor : new Promise(). It has one executor function which has two arguments (resolve, reject).

Promise object has three methods: then(), catch() & finally().

Image for post

If Promise is successfully executed then its data is transferred through resolve function and if it has error then passed through reject function.

We have implemented same task which is done using call back function in Promises and its easily understandable However it is complicated compare to callback function but when you use promises for sometimes then it’s easy to implement.

In _getRollNumber(), _resolve method’s data is caught by then() functions arguments and reject method’s data is caught by catch() function. Here In Promises, Every task has different promises because of that it is easy to debug and readable compare to call back function. You can see that there is no shape like “Pyramid of Doom” in Promises. This is how Callback function is replaced by Promises.

Thank you for reading!

This article was originally published on Medium.com

#javascript-tips #advanced-javascript #javascript #callback-function #promises

A Beginner’s Guide To Promises In JavaScript

Welcome to my post about the JavaScript Promises. I hope it can be helpful since when we start programming it is difficult to enter the context.

Promises are one of the largest tools in the world of JavaScript that helps us to manage future situations in the flow of execution of a program.

The promises originated in the realm of functional programming, generally to handle asynchronous programming. In short, they allow us to define how data that will only be available in the future will be treated, specifying what will be done with that data later.

The promises were introduced in the standard in ES6, the truth is that they have been used for a long time since several libraries had implemented them to solve their needs in a more elegant way.

Image for post

The Promise object represents the eventual completion or failure of an asynchronous operation and its resulting value.

#programming #coding #javascript-promise #promises #javascript