javascript – Why are promises needed?

Question:

I just can't understand their meaning in any way.

Why would I need to write promises or create functions via async / await when I can just put setTimeout ()?

Answer:

Promises are a convenient replacement for callbacks.

Let's imagine we have a function:

const awesomeFunction = () => {
    // ... делаю дела
    // ... делаю дела
}

with them we want to execute another function immediately after the first one is completed:

const awesomeFunction = callback => {
    // ... делаю дела
    // ... делаю дела
    callback()
}

const printFunction = () => {
    // ... что то вывожу в консоль
}

awesomeFunction(printFunction)

We can rewrite it using promises, but so far it won't make much difference, since our code is synchronous:

const awesomeFunction = () => {
    return new Promise (resolve => {
        // ... делаю дела
        // ... делаю дела
        resolve()
    })
}

const printFunction = () => {
    // ... что то вывожу в консоль
}

awesomeFunction().then(printFunction)

Nothing fancy yet, but notice how much clearer it has become with the use of promises and the then () method.

On the example of a single callback, this may not be so noticeable, but if there are many of them, this will save us from the so-called Callback Hell .

If you haven’t come across such a term yet, imagine what the code would look like with hundreds of callbacks nested inside one another.

Presently:

It is enough to understand that promises are the same callbacks, only with a more convenient syntax, which simplify the writing of the code and its support.

Consider the same options for asynchronous code:

const awesomeFunction = callback => {
    // функция printFunction будет 
    // запущена через одну секунду
    setTimeout(callback, 1000)
}

const printFunction = () => {
    // ... что то вывожу в консоль
}

awesomeFunction(printFunction)

Is there a difference with the synchronous option?

For us, it does not exist, we still call our callback exactly when we thought it was necessary, in this particular case, one second after the start of the awesomeFunction .

Let's rewrite to promises:

const awesomeFunction = () => {
    return new Promise (resolve => setTimeout(resolve, 1000))
}

const printFunction = () => {
    // ... что то вывожу в консоль
}

awesomeFunction().then(printFunction)

Assuming printFunction also asynchronous, then we can check them one by one, since now it also returns a promise to us:

const awesomeFunction = () => {
    return new Promise (resolve => setTimeout(resolve, 1000))
}

const printFunction = () => {
    return new Promise (resolve => setTimeout(() => {
        console.log("printed")
        resolve()
    }, 1000))
}

const anotherFunction = () => {
    // ... делаю что нибудь третие
}

awesomeFunction()
   .then(printFunction)
   .then(anotherFunction)

Pay attention to how much clearer this notation of the then then type is compared to the nesting of callbacks.

If we want to transfer something from one function to another, then we can do it like this:

const awesomeFunction = () => {
    return new Promise (resolve => setTimeout(() => {
        resolve("текст для \"print\"")
    }, 1000))
}

const printFunction = text => {
    console.log(text)
}

awesomeFunction().then(text => printFunction(text))

ECMAScript 2017 introduces an even more convenient syntax for working with asynchrony called async / await .

It is based on promises and is essentially no different from them, but it allows us to write asynchronous code in much the same way as synchronous code.

In order to indicate that a particular function is asynchronous, we just need to add the special word async , and before the asynchronous operation the word await :

const awesomeFunction = () => {
    return new Promise (resolve => setTimeout(() => {
        resolve("текст для \"print\"")
    }, 1000))
}

const printFunction = text => {
    console.log(text)
}

// что бы не отходить далеко от предидущих примеров
// я завернул вызовы в IIFE
// что это такое см. ниже

(async() => {
    const text = await awesomeFunction()
    printFunction(text)
})()

// если бы мы делали вызовы из другой функции
// то это выглядело бы так

const parentFunction = async() => {
    const text = await awesomeFunction()
    printFunction(text)
}
    
parentFunction()

What is IIFE

Scroll to Top