我正在使用此授权流程来获取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()
中的第二个承诺在第一个承诺之前执行。为什么会这样呢?我想我可能对Java Promise的工作方式有一个根本性的误解,但是我不确定我到底不了解什么。
答案 0 :(得分:6)
此行未链接诺言
int counter = 0;
int min;
int temp2;
System.out.println("\n\n2. Selection Sort"); // selection
double startTime1 = System.nanoTime();
for (int i = 0; i < list2.size(); i++)
{
min =i;
for (int k = i+1; k < list2.size(); k++)
{
counter++;
if ( list2.get(min) > list2.get(k))
{
min = k;
}
}
temp2 = list2.get(min);
list2.set(min,list2.get(i));
list2.set(i,temp2);
}
double endTime1 = System.nanoTime();
double duration1 = endTime1 - startTime1;
System.out.println("Seconds to sort = " + duration1/1000000000 + " seconds");
System.out.println("Number of iterations = " + counter);
您将函数传递给promise,以便promise可以在函数完成时调用该函数。
通过一个函数,它应该开始工作
.then(
console.log("POST ACCESS TOKEN: " + spotifyApi.getAccessToken())
);