JavaScript >> Javascript 文檔 >  >> JavaScript

JavaScript 中的 Promise:它們是什麼,如何使用它們

Promises 是 JavaScript 的一項功能,它允許代碼在後台繼續執行,並在完成後執行帶有結果的操作。本文將向您展示如何使用 Promises。

什麼是 JavaScript 中的“承諾”?

一個承諾 是 JavaScript 中的一個對象,它充當操作最終結果的佔位符。

承諾是:

  • 操作完成時掛起
  • 操作成功時執行
  • 如果操作失敗則拒絕

Promise 允許在 JavaScript 中異步執行代碼。

同步與異步

異步執行意味著不止一件事可以同時發生。同步代碼是順序的——每一行代碼都一個接一個地執行。代碼在執行成功之前不會執行。

異步編程意味著代碼可以與其他代碼一起執行,完成後返回結果——而不是基於前幾行代碼的執行。例如,您可以設置一個異步函數來從遠程服務器檢索一些數據,並在等待該數據下載的同時繼續執行其他任務。

舊的異步方式——函數回調

JavaScript 是一種同步編程語言。

歷史上,異步任務是在 JavaScript 中使用回調執行的。回調函數是在其他函數完成執行後調用的函數。回調可以是同步的也可以是異步的,通常用於實現異步功能。

通過將一個函數傳遞給另一個函數,可以鏈接回調——每個函數在完成時調用下一個函數,而主腳本繼續執行。

異步代碼的承諾

上述方法很快就會變得混亂。 Promise 是 JavaScript 的一個相對較新的特性,它增加了對異步代碼的原生支持。 Promise 讓你在不暫停腳本執行的情況下等待函數的結果。

Promise JavaScript 語法

Promise 是一個 JavaScript 對象。創建 Promise 時,您需要提供它必須執行的代碼,以及當 Promise 成功或失敗時應採取的操作。

創建承諾

Promise 像其他變量一樣被初始化:

var myPromise = new Promise();

上面,創建了一個 Promise。但它什麼也沒做。必須添加一個函數,其中包含 Promise 將執行並等待的代碼:

var myPromise = new Promise((resolve, reject) => {

    // If your code is successful, call resolve to complete the Promise successfully
    resolve(result);

    // If your code is not successful, call reject
    reject(error);

});

這裡,創建了一個包含函數的 Promise。兩個參數從 Promise 傳遞給函數 - resolve拒絕 . 解決 參數是一個函數,應該使用代碼的成功結果調用,而 reject 如果有問題應該調用函數。

請注意,上述示例中使用了箭頭函數語法。

傳遞給 resolve 的變量 或拒絕 將作為 Promise 的結果提供。

使用 Promise 的結果

一旦 Promise 成功(resolved )或失敗(拒絕 )。這是使用 .then() 完成的 和 catch()

var myPromise = new Promise((resolve, reject) => {

    //  Your code here, calling either resolve() or reject()

});

myPromise.then(result => {
    // The Promise has completed successfully - the result can be accessed using the argument returned by .then()
});

myPromise.catch(error => {
    // The Promise has failed - the error or object passed to reject() can be accessed using the argument returned by .catch()
});

myPromise.finally(() => {
    // The Promise either succeeded or failed - actions can be taken here regardless of the outcome
});

承諾示例

promise 最簡單的演示是設置一個超時時間——一個延遲會延遲 Promise 的解析。您將能夠看到 Promise 執行、時間流逝和結果返回——而其餘代碼繼續執行:

console.log('Hello');

var myPromise = new Promise((resolve, reject) => {

    setTimeout( function() {
        resolve("This is the delayed result of a promise - it's asynchronous!");
    }, 1000)

});

console.log('This message will appear before the one inside the Promise');

myPromise.then(result => {
    console.log(result);
});

如果你執行上面的代碼,你會看到消息並沒有按照它們在代碼中出現的順序出現——promise被延遲了1000毫秒——之後的代碼繼續執行。當 promise 被解析時,結果會被打印出來。

真實示例

JavaScript 可能是最好的示例,也是您可能會使用的示例fetch API。

獲取 API 用於通過 HTTP 訪問遠程數據。由於這些網絡傳輸需要時間,獲取 是異步的,調用時返回一個promise:

fetch('http://example.com/movies.json')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.log(error));

以上,JSON 數據是通過 HTTP 使用 fetch 從示例 URL 加載的 .返回一個 Promise,由兩次調用 then() 處理 – 第一個加載 HTTP 調用的 JSON 結果,第二個使用 console.log() 打印它 .如果發生錯誤,它會被 catch() 捕獲 也打印出來了。

這展示了使用 Promise 的簡潔性——使用箭頭函數語法和 Promises,本來可以通過幾行代碼來實現異步解決方案的一系列混亂的回調。

Tutorial JavaScript 教程
  1. ES2020 可選鏈接示例

  2. 使用 NativeScript-Vue 創建實時位置跟踪應用程序

  3. 使用lazysizes.js 延遲加載任何圖表和廣告

  4. jQuery 代碼文檔 Favelet

  5. jQuery:多個 AJAX 和 JSON 請求,一個回調

  6. 在 AWS API Gateway 訪問無服務器 API 的 API 密鑰身份驗證

  7. 將 PropTypes 反應到流代碼模塊

  1. 在使用 mern-docker 構建 MERN 應用程序時利用 Docker 的強大功能

  2. 讓我們一起製作一個 DEV.to CLI...

  3. 如何將博客文章添加到 github 自述文件?

  4. 貨幣轉換器:瀏覽器擴展

  5. Summarizer - 將任何視頻/音頻轉換為摘要文本

  6. 使用 Amcharts 在生產環境中優化 React App 的大小

  7. 使用 Parcel v2 和 Transcrypt 使用 Python 創建 Web 應用程序

  1. 帶道具上學的狀況

  2. 使用 GitHub Actions 發布/更新 NPM 包

  3. 在 PHP 服務器上使用 JavaScript 進行慢速 Loris 攻擊 [及其預防!]

  4. 如何使用 vuex 進行表單處理