Promises are used to wait for a function to get executed and return the value. Once the value is returned, it will execute the next statements.
Single Promise function in Typescript
console.log("Instruction 1");
console.log("Instruction 2");
apiCall().then((result) => {
console.log(result);
console.log("Instruction 4");
console.log("Instruction 5");
});
function apiCall(): Promise<string> {
return new Promise(resolve => {
setTimeout(() => {
resolve("Instruction 3");
}, 3000);
});
}
Cascading promise function in Typescript
console.log("Instruction 1");
console.log("Instruction 2");
apiCall().then((result) => {
console.log(result);
apiCall2(result).then((result) => {
console.log(result);
console.log("Instruction 4");
console.log("Instruction 5");
})
});
function apiCall(): Promise<string> {
return new Promise(resolve => {
setTimeout(() => {
resolve("Instruction 3");
}, 3000);
});
}
function apiCall2(param: string): Promise<string> {
return new Promise(resolve => {
setTimeout(() => {
resolve(param);
}, 3000);
});
}

0 Comments