I
I
Imp2019-12-16 17:07:14
JavaScript
Imp, 2019-12-16 17:07:14

Calling a function again with a promise?

For example, there is this code

function zapros1() {
    return new Promise((resolve,reject) => {
        request('http://mysite.com/url1', (error,respnse,body) => {
            if(error) return reject(error);
            return resolve(body);
        })
    })
}

function zapros2() {
    return new Promise((resolve,reject) => {
        request('http://mysite.com/url2', (error,respnse,body) => {
            if(error) return reject(error);
            return resolve(body);
        })
    })
}

async function main() {
    try {
        await zapros1();
        await zapros2();
    } catch (error) {
        console.log(error);
    }
}

If we say the site I'm accessing is not stable and an error occurs when calling zapros2(), how would it be correct to repeat the request? Well, for example, 3 attempts to repeat the request. I could call the main() function again, but it's just that the chain of requests can consist of 7 requests, and the error will crash on the 4th. I would not like to re-send 3 previous requests that worked correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SeltonSoer, 2019-12-16
@SeltonSoer

let resultZapros1 = false
async function main() {
    try {
      if (!resultZapros1) {
        await zapros1().then((ok) => {
          if (ok) {
            resultZapros1 = true
          }
        });
      }
        await zapros2().then((error) => {
          ...
        });
    } catch (error) {
        main()
    }
}

Я бы сделал как-то так наверно, во втором варианте добавить условие не забудь.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question