[英]Will Second Promise wait for the First Promise to complete Before it start
[英]In a chained promise, why is the second promise executing before the first promise?
我正在使用此授權流程來獲取Spotify API的訪問令牌。 除非有錯誤,否則這組鏈接的諾言中的第一個諾言將設置access_token
,它將錯誤記錄到控制台。 第二個承諾只是打印出最近設置的訪問令牌。 我認為這段代碼將阻止第二個.then()
內部的代碼執行,直到第一個承諾解決為止。
console.log("PRE ACCESS TOKEN: " + spotifyApi.getAccessToken())
spotifyApi.clientCredentialsGrant().then(
function(data) {
console.log("The access token expires in " + data.body["expires_in"]);
console.log("The access token is " + data.body["access_token"]);
// Save the access token so that it's used in future calls
spotifyApi.setAccessToken(data.body["access_token"]);
},
function(err) {
console.log(
"Something went wrong when retrieving an access token",
err.message
);
}
).then(
console.log("POST ACCESS TOKEN: " + spotifyApi.getAccessToken())
);
但是我得到以下輸出:
PRE ACCESS TOKEN: undefined
POST ACCESS TOKEN: undefined
這意味着在第二個.then()
中的第二個承諾在第一個承諾之前執行。 為什么會這樣呢? 我想我可能對JavaScript的諾言如何運作有根本的誤解,但是我不確定我到底不了解什么。
這條線沒有束縛諾言
.then(
console.log("POST ACCESS TOKEN: " + spotifyApi.getAccessToken())
);
您將函數傳遞給promise,以便promise可以在函數完成時調用該函數。
通過一個函數,它應該開始工作
.then(function() {
console.log("POST ACCESS TOKEN: " + spotifyApi.getAccessToken())
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.