我阅读了有关promise
的说明:
const promise = new Promise((resolve, reject) => {
// Do some async stuff
// If async opp successful
resolve();
// If async opp fails
reject();
});
所以,我试图使用它,但没有成功:
let async = new Promise((resolve, reject)=>{
this.getPerson(page).subscribe( data => {
console.log("First")
});
resolve();
})
async.then((result) =>{
console.log("Last")
});
在控制台,我有"最后"首先,有人给我一个提示?
答案 0 :(得分:0)
您的resolve();
应在this.getPerson(page).subscribe( data => {
喜欢:
let async = new Promise((resolve, reject)=>{
this.getPerson(page).subscribe( data => {
console.log("First")
resolve(); // called asap the result gets from api and above line executed
});
// resolve(); will be called before the above async function get's its response
});
async.then((result) =>{
console.log("Last")
});
注意:不要使用变量名
async
,因为它已经保留了 关键字。
答案 1 :(得分:0)
在查询完成之前,您正在解决承诺。检查以下代码以获取正确的解决方案
let async = new Promise((resolve, reject)=>{
this.getPerson(page).subscribe( data => {
console.log("First");
resolve(); // this is the expected place
});
});
async.then((result) =>{
console.log("Last")
});
答案 2 :(得分:0)
而不是在整个
中使用保留async
关键字
let async = new Promise((resolve, reject)=>{
this.getPerson(page).subscribe( data => {
console.log("First")
});
resolve();
})
async.then((result) =>{
console.log("Last")
});
您可以将代码重写为:
const promise = new Promise((resolve, reject) => {
// Do some async stuff
// If async opp successful
setTimeout(function(){
resolve(console.log("First")
)});
});
promise.then((result) =>{
console.log("Last")
});
这可以解决您的问题。