resolve()然后()首先是异步的东西

时间:2018-03-05 06:27:21

标签: javascript angular promise angular-promise es6-promise

我阅读了有关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")
});

在控制台,我有"最后"首先,有人给我一个提示?

3 个答案:

答案 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")
   });

这可以解决您的问题。