【问题标题】:resolve() and then() comming first than async stuffresolve() 和 then() 先于异步的东西
【发布时间】:2018-08-12 18:19:35
【问题描述】:

我读过一篇关于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")
});

在控制台,我有“Last”在前,有人给我提示吗?

【问题讨论】:

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


    【解决方案1】:

    您的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 这样的变量名,因为它已经保留了 关键字。

    【讨论】:

    • 谢谢!就是这样 :D,谢谢你的留言。
    • @AlexGaspar,请您接受答案,因为我首先给出了答案,您可以投票多个​​答案但只接受一个,您首先接受的答案是我的而不是 Yogi,这使得我的naswer 被接受,您可以在获得 15 次支持后对答案进行投票。
    【解决方案2】:

    您正在完成查询之前解决承诺。检查下面的代码以获取正确的解决位置

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

    【讨论】:

      【解决方案3】:

      而不是使用保留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")
         });

      这应该可以解决您的问题。

      【讨论】:

        猜你喜欢
        • 2015-11-05
        • 2021-08-29
        • 2014-02-09
        • 2020-08-12
        • 2016-06-04
        • 2018-01-13
        • 1970-01-01
        • 1970-01-01
        • 2020-07-22
        相关资源
        最近更新 更多