Javascript訪問Promise對象返回值的操作方法
在Javascript中,什么是Promise
Promise是一個對象,表示一個異步操作的事件完成或失敗。
Promise對象可以是如下狀態(tài):
- pending
- fulfilled
- rejected
最廣泛使用的異步操作的一個實例是Fetch API。fetch() 方法返回一個Promise對象。
如果我們從后端API獲取一些數(shù)據(jù)。對于這篇博文,我將使用JSONPlaceholder – 一個偽造的REST API。我們將獲取一個id=1的用戶數(shù)據(jù)。
fetch("https://jsonplaceholder.typicode.com/users/1")讓我們看看如何訪問返回數(shù)據(jù)。
1- then() 鏈式操作
它是最簡單和最明顯的方式。
fetch("https://jsonplaceholder.typicode.com/users/1") // 1
.then((response)=>response.json()) //2
.then((user) => {
console.log(user.address); // 3
});這里,我們(1)從API獲取數(shù)據(jù),(2)轉(zhuǎn)換為JSON對象,然后(3)打印用戶地址值到控制臺。
結(jié)果如下:
{
street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874',
geo: { lat: '-37.3159', lng: '81.1496' }
}
2- 在之后的代碼中使用返回值
但是如果我們想要在之后的代碼中使用返回值,怎么辦?
如果我們嘗試像這樣做(錯誤方式?。?/p>
const address = fetch("https://jsonplaceholder.typicode.com/users/1")
.then((response)=>response.json())
.then((user) => {
return user.address;
});
console.log(address);我們將得到
Promise { <pending> }得到這種結(jié)果,是因為Javascript代碼總是同步執(zhí)行,所以console.log()函數(shù)在fetch()請求后立即開始,而沒有等待直到它解析完成。當(dāng)console.log()函數(shù)開始運行的時刻,fetch()請求函數(shù)返回的Promise對象處于pending狀態(tài)。
那就是說,我們可以訪問另一個 .then() 回調(diào)函數(shù)的Promise對象的返回值:
const address = fetch("https://jsonplaceholder.typicode.com/users/1")
.then((response) => response.json())
.then((user) => {
return user.address;
});
const printAddress = () => {
address.then((a) => {
console.log(a);
});
};
printAddress();或使用async/await語法:
const address = fetch("https://jsonplaceholder.typicode.com/users/1")
.then((response) => response.json())
.then((user) => {
return user.address;
});
const printAddress = async () => {
const a = await address;
console.log(a);
};
printAddress();以這兩種方式,我們將得到:
{
street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874',
geo: { lat: '-37.3159', lng: '81.1496' }
}結(jié)論
Promise對象廣泛用于Javascript異步編程。而且開發(fā)者對于如何正確使用它,有時還有些困惑。在這篇博客文章里,我已經(jīng)試圖描述一個用戶例子,即當(dāng)開發(fā)者需要在之后的代碼中使用來自Promise對象的返回值的實例。
英文原文鏈接:https://dev.to/ramonak/javascript-how-to-access-the-return-value-of-a-promise-object-1bck
更多中文參考資料
[1] JavaScript Promise - Javascript教程. https://www.runoob.com/js/js-promise.html
[2] JavaScript Promise 對象 – 編程技術(shù). https://www.runoob.com/w3cnote/javascript-promise-object.html
[3] 7.6 Promise – 7. 瀏覽器 – JAVASCRIPT教程- 廖雪峰的官方網(wǎng)站. https://liaoxuefeng.com/books/javascript/browser/promise/index.html
到此這篇關(guān)于Javascript如何訪問Promise對象返回值的文章就介紹到這了,更多相關(guān)js訪問Promise對象返回值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
微信小程序自定義yPicker組件實現(xiàn)省市區(qū)三級聯(lián)動功能
這篇文章主要介紹了微信小程序自定義yPicker組件分析及省市區(qū)三級聯(lián)動實現(xiàn),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10
Javascript 定時器調(diào)用傳遞參數(shù)的方法
Javascript 定時器調(diào)用傳遞參數(shù)的方法,需要的朋友可以參考下。2009-11-11
利用 JavaScript 實現(xiàn)并發(fā)控制的示例代碼
這篇文章主要介紹了利用 JavaScript 實現(xiàn)并發(fā)控制的示例代碼,本文通過實例代碼給大家介紹的非常想詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12

