尚未解决Promise解决方案的结果如何?

时间:2019-02-23 07:40:53

标签: javascript asynchronous promise

如果已解决承诺,则输出中的回购方式不确定。

代码输出为:

  

从数据库中读取........

     

你好

     

存储库为:未定义

     

从存储库中读取

getuser(1)
                .then( result =>{console.log('hello');getRepository(result.username)})
                .then( repos =>console.log('repos are :',repos));

相关的异步功能是

function getuser(id){
return new Promise((resolve,reject)=>{
    setTimeout(() => {
        console.log('reading from database........')
        resolve({id:id , username:"sunil"});
    }, 5000);
});

}

function getRepository(username){
return new Promise((resolve,reject)=>{
    setTimeout(()=>{
        console.log('reading from repository')
        resolve(['repos1','repos2','repos3']);  
    }
     ,3000);
})

}

2 个答案:

答案 0 :(得分:2)

您的第一个.then没有返回任何内容,因此它立即解决。更改为return getRepository(...

答案 1 :(得分:1)

您的代码应为

getuser(1)
          .then( result =>{console.log('hello');
                 return getRepository(result.username)})
          .then( repos =>console.log('repos are :',repos));