0

I would like to use the got library to make http requests; wit utilizing the Promises correctly.

I have already tried using Promises in my code, and they never work as expected.

Consider the following pseudo-code:

function getToken() {
    var response = new Request('https://my-api/get-token')
}

// First, I need to get a token
my_token = getToken();

// Now I can perform actions with it
var folderID = createFolder(my_token, '/root')
renameFolder(my_token, folderID, 'foo_bar')
deleteFolder(my_token, folderID)

As you can see, everything needs to be done synchronously.

  1. First, I need to get a token from the website
  2. Then I create something using the token
  3. Then I work on the created thing

This possibly can't be done using Promises as documented in the got library: https://www.npmjs.com/package/got#usage

I'm at lost on what to do. They don't even provide any examples.

Help me please?

ConfusedGuy
  • 121
  • 9
  • It would be better for you to learn how to effectively use Promises than to try to perform inherently asynchronous operations without them. Even in cases where it is remotely possible, trying to treat asynchronous processes as though they were synchronous just leaves you with a big steaming mess of code. – Abion47 Feb 01 '19 at 19:55
  • @Abion47 I have a problem with the concept of asynchronous operations where the http calls are required to be procedural (e.g. fetching a token from the REST api that I need to work with in the subsequent calls). I tried to learn Promises (and await/async) in the past week to no avail. Can you please suggest any resources that could teach me how what I'm asking is typically done in Node? – ConfusedGuy Feb 01 '19 at 20:04
  • This is how JS works. Once the code is **a**synchronous, it cannot become synchronous - because this means that it's not synchronous, literally. If If you hate how JS works so much you can't adopt it, you jumped the wrong train, consider using PHP or other language that allows to write synchronous code. SO isn't the best place to ask for learning resources because this is against rules. Try Reddit. – Estus Flask Feb 01 '19 at 20:06
  • 4
    Writing asynchronous code in a synchronous way is the whole idea behind `async` and `await`. There are a bunch of resources you can pull from to learn how they work, such as [this one](https://blog.risingstack.com/mastering-async-await-in-nodejs/). – Abion47 Feb 01 '19 at 20:07
  • @Abion47 thanks for the resource. – ConfusedGuy Feb 01 '19 at 20:26
  • @estus If there is a problem with the way I am thinking, I prefer to correct my idea, instead of falling back to other languages. I considered PHP, but isn't that a dead language by now, anyways? – ConfusedGuy Feb 01 '19 at 20:27
  • 1
    I wouldn't call it a _dead_ language, as there are still plenty of web services that use it. If anyone told me that they wanted to use it for a new project, though, they'd better have a damn good reason or I'd call them insane. – Abion47 Feb 01 '19 at 20:28
  • 1
    @estus I can't +1 your comment yet, but I really like what you said "Once the code is asynchronous, it cannot become synchronous" part. _That_ is a crucial thing I need to understand to be able to write code like that. – ConfusedGuy Feb 01 '19 at 20:30
  • On a general note, is it possible (or a good idea) to use Promises like callbacks? That idea is more tolerable to me than the way Promises are presented in every guide I read or course I take. – ConfusedGuy Feb 01 '19 at 20:30
  • @ConfusedGuy Regarding sync-async, this is exactly what the question I marked as a dupe is dedicated to. Promises actually use callbacks, you will use them with `then` and `catch`. Promise pattern is based on callbacks but provides several major benefits over plain callbacks like Node-style error-first callbacks. async/await is just syntactic sugar for promises that allows to write them in sync-like way. Every `async` function can be rewritten to use raw promises. I'd suggest to start with raw promises and then learn what corresponding async/await syntax looks like. – Estus Flask Feb 01 '19 at 20:47

1 Answers1

4

You should never make synchronous requests they block the thread, that would be catastrophic on a server and synchronous requests have been deprecated for a long time on the client too.

I think you have some learning to do about async code, but in the mean time did you look at the docs? The first snippet shows how trivial it is to work with async using asyc/await:

const got = require('got');

(async () => {
    try {
        const response = await got('https://sindresorhus.com');
        const token = response.body;
        // ... do stuff with token
        const nextResponse = await got('http://sindresorhus.com', {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        })
    } catch (error) {
        console.error(error.response.body);
    }
})();
Dominic
  • 62,658
  • 20
  • 139
  • 163
  • The problem with the docs is that the example is not chain-able, I would like to acquire a token key which should be used on subsequent http calls. Can you edit your answer to reflect how can I _asynchronously_ perform procedural requests using [got](https://www.npmjs.com/package/got#usage)? – ConfusedGuy Feb 01 '19 at 20:01
  • 2
    @ConfusedGuy It's chainable. "subsequent http calls" go to "do stuff with token". That's the benefit of async/await. It looks like synchronous code. – Estus Flask Feb 01 '19 at 20:12
  • @Dominic do I just write the rest of calls in "do stuff with token" line after line? Also, what if I want to wrap some requests in a function? (e.g. the token process should be in `getToken()`) – ConfusedGuy Feb 01 '19 at 20:23
  • @ConfusedGuy I updated my answer, as estus said you can simply write code which looks synchronous, but it's actually allowing other things to run while it's waiting for the response – Dominic Feb 01 '19 at 20:53