0

I have been learning how to use callback with stupid callback hell.

This is an example I have created: https://jsfiddle.net/1donpcvv/

It is working as expected. step1() has to complete first and then move on to step2() and then finally step3()

I am trying to convert to promise which I am struggling to get it work. What did I do wrong?

JS:

function step1() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log("Step 1 done After 3 seconds");
            resolve();
        }, 3000);
    });
}

function step2() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log("Step 2 done After 2 seconds");
            resolve();
        }, 2000);
    });
}

function step3() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log("Step 3 done After 1 seconds");
            resolve();
        }, 1000);
    });
}

Usage

step1().then().step2().then().step3();
user88432
  • 397
  • 1
  • 4
  • 13

2 Answers2

1

The syntax for chaining promises is:

step1().then(step2).then(step3);

... so you provide callback arguments to then.

In less trivial cases where you maybe use the promised value and/or arguments, you could use bind or inline function expressions:

step1().then(result => step2(result)).then(result2 => step3(result2));
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Ahhh, I was almost there. Thats nice. Is there a way without adding `new Promise()` on each step method? – user88432 Apr 15 '18 at 20:38
  • 1
    Sure, just promisify `setTimeout`, like I described in the end of [this answer](https://stackoverflow.com/a/40329190/5459839). – trincot Apr 15 '18 at 20:40
0

Welcome to async/await syntax

async function bar () {
    await step1();
    await step2();
    await step3();
}

bar()
  .then(() => {/*After bar execution here*/})
  .catch(err => console.error('some step reject', err))

function step1() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log("Step 1 done After 3 seconds");
            resolve();
        }, 3000);
    });
}

function step2() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log("Step 2 done After 2 seconds");
            resolve();
        }, 2000);
    });
}

function step3() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log("Step 3 done After 1 seconds");
            resolve();
        }, 1000);
    });
}

You can manage rejects with try...catch

async function bar () {
    try {
        await step1();
        await step2();
        await step3();
    } catch (e) {
        console.error('some step reject', e)
    }
}

and bar is like

bar().then(() => {/*After bar execution here*/})

or

async function foo () {
    await bar()
}
Fernando Carvajal
  • 1,869
  • 20
  • 19