我是NodeJ的初学者。我们都知道promise也是在nodeJS中以同步方式执行的方法之一。在我的代码中,它不是同步执行的。有人可以告诉我我的代码有什么问题吗?我已经在下面的代码中附加了代码,并输出了我现在所得到的信息。任何评论将不胜感激。谢谢...
代码:
getUser(25)
.then((user)=>{
console.log(`User:`,user.username);
getgithubRepo(user.username);
})
.then((repos)=>{
console.log("Repos:",repos);
getCommit(repos[1]);
})
.then((message)=>{
console.log(`Final Message: ${message}`);
})
.catch((err)=>{
console.log(`Reject: ${err}`);
});
function getUser(id){
return new Promise((resolve,reject)=>{
if(id === 25){
setTimeout(()=>{
console.log(`Id: ${id}`);
console.log(`Reading a user from database`);
resolve({id:id,username:'vigneshTokyo'});
},3000);
}
else{
setTimeout(()=>{
console.log(`Your given Id is not found...`);
reject(`User not found in database`);
},3000);
}
});
}
function getgithubRepo(username){
return new Promise((resolve,reject)=>{
if(username === "vigneshTokyo"){
setTimeout(()=>{
console.log(`Username: ${username}`);
console.log(`Calling Github API...`);
const repos=['vikirepo1','vikirepo2','vikirepo3'];
resolve(repos);
},2000);
}
else{
setTimeout(()=>{
console.log(`Repositories are not found of this username`);
reject(`Repositories are not found of this username`);
},2000);
}
});
}
function getCommit(repo){
return new Promise((resolve,reject)=>{
if(repo === "vikirepo2"){
setTimeout(()=>{
console.log(`Repository Name: ${repo}`);
console.log(`Going to commit this ${repo}.....`);
return resolve('Repo commited succesfully');
},2000);
}
else{
setTimeout(()=>{
return reject('Repos not found in this account');
},2000);
}
});
}
输出:
Id: 25
Reading a user from database
User: vigneshTokyo
Repos: undefined
Reject: TypeError: Cannot read property '1' of undefined
Username: vigneshTokyo
Calling Github API...
Expected output:
Id: 25
Reading a user from database
Resolve: { id: 25, username: 'vigneshTokyo' }
Username: vigneshTokyo
Calling Github API...
List of Repostories: [ 'vikirepo1', 'vikirepo2', 'vikirepo3' ]
Repository Name: vikirepo2
Going to commit this vikirepo2.....
Message: Repo commited succesfully