postPersonalDetails(pdData){
let options : RequestOptionsArgs;
let token:string;
let id:string;
this.getToken().then((val) => {
token = val;
console.log("I am in token func"+token);
});
this.storage.get('userID').then((val) => {
id = val;
console.log(val);
});
console.log("I amhere"+token+id);我正在获取第1个consoleLog和第2个控制台日志中的数据
由于异步的本质,第三控制台日志首先打印,我得到的令牌是未定义的,用户ID也是未定义的,这样做的正确方法是什么?
发布于 2017-08-14 02:07:01
angular设置附带core-js和用于Promise的polyfill。您可以将您的承诺与Promise.all (see MDN with a detailed method explanation)合并,然后在两个承诺都得到解决后继续。
Promise.all([
promise1, promise2, ...
])请记住,如果组合承诺中的一个被拒绝,Promise.all就会拒绝。
发布于 2017-08-14 08:33:35
以下是关于PerfectPixel提议的更多细节。
const promise1 = this.getToken().then((val) => {
console.log("I am in token func"+val);
return val;
});
const promise2 = this.storage.get('userID').then((val) => {
console.log(val);
return val;
});
Promise
.all([promise1, promise2])
.then((results) => {
const [ token, id ] = results;
console.log("I am here"+token+id);
});
}这是一个更通用的例子。(有关副作用的更多详细信息,请参阅Bergi的评论。)
const promise1 = Promise.resolve("the-token").then((val) => {
console.log("I am in token func: " + val);
return val;
});
const promise2 = Promise.resolve("the-userID").then((val) => {
console.log("I am in id func: " + val);
return val;
});
Promise.all([promise1, promise2]).then((results) => {
const [ token, id ] = results;
console.log("I am here: " + token + " " + id);
});
https://stackoverflow.com/questions/45662859
复制相似问题